<?php

namespace App\Http\Controllers\Admin\Manage\Purchase;

use App\Http\Controllers\Concerns\FlashesEntityMessage;
use App\Http\Controllers\Concerns\ParsesDataTableQuery;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Manage\PurchaseRequest;
use App\Models\Purchase;
use App\Services\Manage\PurchaseService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class PurchaseController extends Controller
{
    use FlashesEntityMessage, ParsesDataTableQuery;

    public function __construct(
        private readonly PurchaseService $purchaseService,
    ) {}

    public function index(Request $request): Response
    {
        $tableQuery = $this->parseDataTableQuery($request);

        return Inertia::render('admin/manage/purchases/Index', [
            'purchases' => $this->purchaseService->paginateForIndex($tableQuery),
            'filters' => $this->dataTableFilters($tableQuery),
        ]);
    }

    public function create(Request $request): Response
    {
        $user = $request->user();

        return Inertia::render('admin/manage/purchases/Create', [
            'suppliers' => $this->purchaseService->supplierOptions(),
            'catalog' => $this->purchaseService->catalogItems(user: $user),
            'draftItems' => $this->purchaseService->draftItemsForUser($user),
        ]);
    }

    public function store(PurchaseRequest $request): RedirectResponse
    {
        $this->purchaseService->create($request->validated(), $request->user());

        $this->flashSuccess('Belanja berhasil diajukan dan menunggu verifikasi owner.');

        return redirect()->route('admin.manage.purchases.index');
    }

    public function edit(Purchase $purchase): Response
    {
        return Inertia::render('admin/manage/purchases/Edit', [
            'purchase' => $this->purchaseService->findForEdit($purchase),
            'suppliers' => $this->purchaseService->supplierOptions(),
            'catalog' => $this->purchaseService->catalogItems($purchase),
        ]);
    }

    public function update(PurchaseRequest $request, Purchase $purchase): RedirectResponse
    {
        $this->purchaseService->update($purchase, $request->validated(), $request->user());

        $this->flashSuccess('Perubahan belanja berhasil diajukan dan menunggu verifikasi owner.');

        return redirect()->route('admin.manage.purchases.index');
    }

    public function destroy(Request $request, Purchase $purchase): RedirectResponse
    {
        $this->purchaseService->delete($purchase, $request->user());

        $this->flashSuccess('Penghapusan belanja berhasil diajukan dan menunggu verifikasi owner.');

        return redirect()->route('admin.manage.purchases.index');
    }
}
