<?php

namespace App\Http\Controllers\Api\Inventory;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Requests\Inventory\SupplierIndexRequest;
use App\Http\Requests\Inventory\SupplierStoreRequest;
use App\Http\Requests\Inventory\SupplierUpdateRequest;
use App\Http\Resources\Inventory\SupplierResource;
use App\Services\Inventory\SupplierService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class SupplierController extends BaseApiController
{
    public function __construct(private SupplierService $suppliers)
    {
        parent::__construct();
    }

    public function index(SupplierIndexRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $perPage = (int) ($payload['per_page'] ?? 20);
        $result = $this->suppliers->list($payload, $perPage);

        return $this->success([
            'suppliers' => SupplierResource::collection($result['items']),
            'pagination' => $result['pagination'],
        ]);
    }

    public function store(SupplierStoreRequest $request): JsonResponse
    {
        $result = $this->suppliers->create($request->validated());
        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Failed to save supplier.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->respondCreated(new SupplierResource($result['supplier']));
    }

    public function update(SupplierUpdateRequest $request, int $id): JsonResponse
    {
        $result = $this->suppliers->update($id, $request->validated());
        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Failed to update supplier.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->success(new SupplierResource($result['supplier']));
    }

    public function destroy(int $id): JsonResponse
    {
        $result = $this->suppliers->delete($id);
        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Failed to delete supplier.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->respondDeleted();
    }
}
