<?php

namespace App\Http\Controllers\Admin\Master\RawMaterial;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Master\RawMaterial\RawMaterialRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\RawMaterial;
use App\Services\Admin\Master\RawMaterial\RawMaterialService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class RawMaterialController extends Controller
{
    public function __construct(
        private RawMaterialService $service,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        return Inertia::render('admin/master/raw-material/index', [
            'rawMaterials' => $this->service->paginated(
                ...$request->validatedWithDefaults(),
                filters: $request->only(['is_active', 'stock', 'name']),
            ),
            'rawMaterialNames' => $this->service->getNames(),
            'filters' => $request->only(['is_active', 'stock', 'name']),
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('admin/master/raw-material/create');
    }

    public function store(RawMaterialRequest $request): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->store($request->validated()),
            'Bahan baku berhasil ditambahkan.',
            'admin.master.raw-materials.index',
            'admin.master.raw-materials.create'
        );
    }

    public function edit(RawMaterial $rawMaterial): Response
    {
        return Inertia::render('admin/master/raw-material/edit', [
            'rawMaterial' => $this->service->getForEdit($rawMaterial),
        ]);
    }

    public function update(RawMaterialRequest $request, RawMaterial $rawMaterial): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->update($rawMaterial, $request->validated()),
            'Bahan baku berhasil diperbarui.',
            'admin.master.raw-materials.index',
            'admin.master.raw-materials.edit',
            ['rawMaterial' => $rawMaterial]
        );
    }

    public function destroy(RawMaterial $rawMaterial): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->destroy($rawMaterial),
            'Bahan baku berhasil dihapus.',
            'admin.master.raw-materials.index'
        );
    }

    public function toggleStatus(RawMaterial $rawMaterial): RedirectResponse
    {
        $this->service->toggleStatus($rawMaterial);
        $status = $rawMaterial->fresh()->is_active ? 'Aktif' : 'Non Aktif';

        Inertia::flash('toast', ['type' => 'success', 'message' => "Status bahan baku berhasil diubah menjadi {$status}."]);

        return back();
    }
}
