<?php

namespace App\Http\Controllers\Admin\Manage;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Manage\PurchaseRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\Purchase;
use App\Services\Admin\Manage\PurchaseService;
use App\Services\Admin\Master\RawMaterial\RawMaterialVariantService;
use App\Services\Admin\Master\SupplierService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class PurchaseController extends Controller
{
    public function __construct(
        private readonly PurchaseService $service,
        private readonly SupplierService $supplierService,
        private readonly RawMaterialVariantService $rawMaterialVariantService,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        return Inertia::render('admin/manage/purchase/index', [
            'purchases' => $this->service->paginated(
                ...$request->validatedWithDefaults(),
                filters: $request->only(['supplier_id']),
            ),
            'suppliers' => $this->supplierService->getAll(),
            'filters' => $request->only(['supplier_id']),
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('admin/manage/purchase/create', [
            'suppliers' => $this->supplierService->getAll(),
            'rawMaterials' => $this->rawMaterialVariantService->getForCutting(),
        ]);
    }

    public function store(PurchaseRequest $request): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->store($request->validated()),
            'Belanja berhasil ditambahkan.',
            'admin.manage.purchases.index',
            'admin.manage.purchases.create'
        );
    }

    public function edit(Purchase $purchase): Response
    {
        return Inertia::render('admin/manage/purchase/edit', [
            'purchase' => $this->service->getForEdit($purchase),
            'suppliers' => $this->supplierService->getAll(),
            'rawMaterials' => $this->rawMaterialVariantService->getForCutting(),
        ]);
    }

    public function update(PurchaseRequest $request, Purchase $purchase): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->update($purchase, $request->validated()),
            'Belanja berhasil diperbarui.',
            'admin.manage.purchases.index',
            'admin.manage.purchases.edit',
            ['purchase' => $purchase]
        );
    }

    public function destroy(Purchase $purchase): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->destroy($purchase),
            'Belanja berhasil dihapus.',
            'admin.manage.purchases.index'
        );
    }
}
