<?php

namespace App\Http\Controllers\Admin\Master;

use App\Enums\RawMaterialUnit;
use App\Http\Controllers\Concerns\FlashesEntityMessage;
use App\Http\Controllers\Concerns\ParsesDataTableQuery;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Master\RawMaterialRequest;
use App\Http\Requests\Admin\ToggleStatusRequest;
use App\Models\RawMaterial;
use App\Services\Master\RawMaterialService;
use App\Support\Media\MediaPresenter;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class RawMaterialController extends Controller
{
    use FlashesEntityMessage, ParsesDataTableQuery;

    public function __construct(
        private readonly RawMaterialService $rawMaterialService,
    ) {}

    public function index(Request $request): Response
    {
        $tableQuery = $this->parseDataTableQuery($request);
        $tableQuery['search_id'] = $request->string('search_id')->trim()->toString();
        $isActive = $request->string('is_active')->toString();
        $stockStatus = $request->string('stock_status')->toString();
        $rawMaterialId = $request->string('raw_material_id')->toString();

        return Inertia::render('admin/master/raw-materials/Index', [
            'rawMaterials' => $this->rawMaterialService->paginateForIndex($tableQuery, $isActive, $stockStatus, $rawMaterialId),
            'filters' => $this->dataTableFilters($tableQuery, [
                'is_active' => $isActive,
                'stock_status' => $stockStatus,
                'raw_material_id' => $rawMaterialId,
                'search_id' => $tableQuery['search_id'],
            ]),
            'rawMaterialsList' => RawMaterial::query()->orderBy('name')->get(['id', 'name'])->map(fn ($r) => ['value' => (string) $r->id, 'label' => $r->name])->all(),
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('admin/master/raw-materials/Create', [
            'units' => RawMaterialUnit::selectOptions(),
        ]);
    }

    public function store(RawMaterialRequest $request): RedirectResponse
    {
        $this->rawMaterialService->create($request->validated(), $request->user());
        $this->flashCreated('Bahan baku');

        return redirect()->route('admin.master.raw_materials.index');
    }

    public function edit(RawMaterial $rawMaterial): Response
    {
        return Inertia::render('admin/master/raw-materials/Edit', [
            'units' => RawMaterialUnit::selectOptions(),
            'rawMaterial' => $this->rawMaterialService->findForEdit($rawMaterial),
        ]);
    }

    public function update(RawMaterialRequest $request, RawMaterial $rawMaterial): RedirectResponse
    {
        $this->rawMaterialService->update($rawMaterial, $request->validated(), $request->user());
        $this->flashUpdated('Bahan baku');

        return redirect()->route('admin.master.raw_materials.index');
    }

    public function destroy(Request $request, RawMaterial $rawMaterial): RedirectResponse
    {
        $this->rawMaterialService->delete($rawMaterial, $request->user());
        $this->flashDeleted('Bahan baku');

        return redirect()->route('admin.master.raw_materials.index');
    }

    public function toggleStatus(ToggleStatusRequest $request, RawMaterial $rawMaterial): RedirectResponse
    {
        $this->rawMaterialService->toggleStatus($rawMaterial, $request->validated(), $request->user());
        $this->flashStatusUpdated('bahan baku');

        return back();
    }

    public function show(RawMaterial $rawMaterial): JsonResponse
    {
        $rawMaterial->load([
            'prices' => fn ($query) => $query->orderBy('created_at')->with('media'),
        ]);

        $rawMaterial->prices->each(function ($price) use ($rawMaterial): void {
            $price->setAttribute('images', MediaPresenter::collection($price, 'images'));
            $price->setAttribute('unit_abbreviation', $rawMaterial->unit->abbreviation());
            $price->unsetRelation('rawMaterial');
        });

        return response()->json($rawMaterial);
    }
}
