<?php

namespace App\Http\Controllers\Api\Inventory;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Inventory\InventoryAdjustRequest;
use App\Http\Requests\Inventory\InventoryAuditRequest;
use App\Http\Requests\Inventory\InventoryItemIndexRequest;
use App\Http\Requests\Inventory\InventoryItemStoreRequest;
use App\Http\Requests\Inventory\InventoryItemUpdateRequest;
use App\Http\Requests\Inventory\InventoryTeacherDistributionRequest;
use App\Http\Requests\Inventory\InventoryTeacherDistributionStoreRequest;
use App\Http\Resources\Inventory\InventoryItemResource;
use App\Services\Inventory\InventoryItemService;
use App\Services\Inventory\InventorySummaryService;
use App\Services\Inventory\InventoryTeacherDistributionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class InventoryController extends BaseApiController
{
    public function __construct(
        private InventoryItemService $items,
        private InventorySummaryService $summary,
        private InventoryTeacherDistributionService $distribution
    ) {
        parent::__construct();
    }

    public function index(InventoryItemIndexRequest $request): JsonResponse
    {
        $result = $this->items->list($request->validated());

        return $this->success([
            'type' => $result['type'],
            'items' => InventoryItemResource::collection($result['items']),
            'categories' => $result['categories'],
            'conditionOptions' => $result['conditionOptions'],
            'schoolYears' => $result['schoolYears'],
            'selectedYear' => $result['selectedYear'],
            'currentYear' => $result['currentYear'],
            'semester' => $result['semester'],
            'userNames' => $result['userNames'],
        ]);
    }

    public function show(int $id): JsonResponse
    {
        $item = $this->items->find($id);
        if (!$item) {
            return $this->error('Item not found.', Response::HTTP_NOT_FOUND);
        }

        return $this->success(new InventoryItemResource($item));
    }

    public function store(InventoryItemStoreRequest $request): JsonResponse
    {
        $result = $this->items->create($request->validated(), (int) auth()->id());
        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Failed to create item.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->respondCreated(new InventoryItemResource($result['item']));
    }

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

        return $this->success(new InventoryItemResource($result['item']));
    }

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

        return $this->respondDeleted();
    }

    public function audit(InventoryAuditRequest $request, int $id): JsonResponse
    {
        $result = $this->items->auditClassroom($id, $request->validated(), (int) auth()->id());
        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Failed to audit item.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->success(new InventoryItemResource($result['item']));
    }

    public function adjust(InventoryAdjustRequest $request, int $id): JsonResponse
    {
        $result = $this->items->adjustStock($id, $request->validated(), (int) auth()->id());
        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Failed to adjust stock.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->success();
    }

    public function summary(string $type): JsonResponse
    {
        $payload = $this->summary->summary($type, request()->query('school_year'));
        return $this->success($payload);
    }

    public function summaryAll(): JsonResponse
    {
        $payload = $this->summary->summaryAll(
            request()->query('school_year'),
            request()->query('type')
        );
        return $this->success($payload);
    }

    public function teacherDistribution(InventoryTeacherDistributionRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $result = $this->distribution->formData(
            (int) auth()->id(),
            $payload['class_section_id'] ?? null,
            $payload['item_id'] ?? null
        );

        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Unable to load distribution form.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->success($result);
    }

    public function teacherDistributionStore(InventoryTeacherDistributionStoreRequest $request): JsonResponse
    {
        try {
            $result = $this->distribution->distribute((int) auth()->id(), $request->validated());
        } catch (\Throwable $e) {
            Log::error('Inventory distribution failed: ' . $e->getMessage());
            return $this->error('Unable to distribute inventory.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Unable to distribute inventory.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->success($result);
    }
}
