<?php

namespace App\Http\Controllers\Admin\Master;

use App\Http\Controllers\Concerns\FlashesEntityMessage;
use App\Http\Controllers\Concerns\ParsesDataTableQuery;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Master\CustomerRequest;
use App\Models\Customer;
use App\Services\Master\CustomerService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class CustomerController extends Controller
{
    use FlashesEntityMessage, ParsesDataTableQuery;

    public function __construct(
        private readonly CustomerService $customerService,
    ) {}

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

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

    public function store(CustomerRequest $request): RedirectResponse
    {
        $this->customerService->create($request->validated());

        $this->flashCreated('Pelanggan');

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

    public function update(CustomerRequest $request, Customer $customer): RedirectResponse
    {
        $this->customerService->update($customer, $request->validated());

        $this->flashUpdated('Pelanggan');

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

    public function destroy(Customer $customer): RedirectResponse
    {
        $this->customerService->delete($customer);

        $this->flashDeleted('Pelanggan');

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

    public function storeApi(CustomerRequest $request): JsonResponse
    {
        $customer = $this->customerService->createAndReturn($request->validated());

        return response()->json([
            'id' => $customer->id,
            'name' => $customer->name,
        ]);
    }
}
