<?php

namespace App\Http\Controllers\Api\Finance;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\PurchaseOrders\PurchaseOrderIndexRequest;
use App\Http\Resources\PurchaseOrders\PurchaseOrderItemResource;
use App\Http\Resources\PurchaseOrders\PurchaseOrderResource;
use App\Models\PurchaseOrder;
use App\Services\PurchaseOrders\PurchaseOrderCreateService;
use App\Services\PurchaseOrders\PurchaseOrderQueryService;
use App\Services\PurchaseOrders\PurchaseOrderReceiveService;
use App\Services\PurchaseOrders\PurchaseOrderStatusService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use RuntimeException;

class PurchaseOrderController extends BaseApiController
{
    public function __construct(
        private PurchaseOrderQueryService $queryService,
        private PurchaseOrderCreateService $createService,
        private PurchaseOrderReceiveService $receiveService,
        private PurchaseOrderStatusService $statusService
    ) {
        parent::__construct();
    }

    public function index(PurchaseOrderIndexRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $orders = $this->queryService->list($payload['q'] ?? null);

        return response()->json([
            'ok' => true,
            'orders' => PurchaseOrderResource::collection($orders),
        ]);
    }

    public function options(): JsonResponse
    {
        $data = $this->queryService->options();

        return response()->json([
            'ok' => true,
            'suppliers' => $data['suppliers'] ?? [],
            'supplies' => $data['supplies'] ?? [],
        ]);
    }

    public function show(int $id): JsonResponse
    {
        $data = $this->queryService->find($id);
        if (!$data) {
            return response()->json(['ok' => false, 'message' => 'Purchase order not found.'], 404);
        }

        return response()->json([
            'ok' => true,
            'purchase_order' => new PurchaseOrderResource($data['purchase_order']),
            'items' => PurchaseOrderItemResource::collection($data['items'] ?? []),
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $data = array_merge($request->query->all(), $request->all(), $request->json()->all());
        $validator = Validator::make($data, [
            'po_number' => ['required', 'string', 'max:60'],
            'supplier_id' => ['required', 'integer', 'min:1', 'exists:suppliers,id'],
            'status' => ['nullable', 'string', 'in:' . implode(',', PurchaseOrder::allowedStatuses())],
            'order_date' => ['nullable', 'date'],
            'expected_date' => ['nullable', 'date'],
            'notes' => ['nullable', 'string', 'max:5000'],
            'items' => ['required', 'array', 'min:1'],
            'items.*.supply_id' => ['required', 'integer', 'min:1', 'exists:supplies,id'],
            'items.*.description' => ['nullable', 'string', 'max:1000'],
            'items.*.quantity' => ['required', 'integer', 'min:1'],
            'items.*.unit_cost' => ['required', 'numeric', 'min:0'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $payload = $validator->validated();
        if (!empty($payload['order_date']) && !empty($payload['expected_date'])) {
            $orderTs = strtotime((string) $payload['order_date']);
            $expectedTs = strtotime((string) $payload['expected_date']);
            if ($orderTs !== false && $expectedTs !== false && $expectedTs < $orderTs) {
                return response()->json([
                    'message' => 'Validation failed.',
                    'errors' => ['expected_date' => ['The expected date must be on or after the order date.']],
                ], 422);
            }
        }

        try {
            $po = $this->createService->create($payload);
        } catch (RuntimeException $e) {
            return response()->json(['ok' => false, 'message' => $e->getMessage()], 422);
        } catch (\Throwable $e) {
            return response()->json(['ok' => false, 'message' => 'Unable to create purchase order.'], 500);
        }

        return response()->json([
            'ok' => true,
            'purchase_order' => new PurchaseOrderResource($po),
        ], 201);
    }

    public function receive(Request $request, int $id): JsonResponse
    {
        $data = array_merge($request->query->all(), $request->all(), $request->json()->all());
        $validator = Validator::make($data, [
            'items' => ['required', 'array', 'min:1'],
            'items.*.id' => ['required', 'integer', 'min:1'],
            'items.*.quantity' => ['required', 'integer', 'min:1'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $payload = $validator->validated();

        $po = PurchaseOrder::query()->find($id);
        if (!$po) {
            return response()->json(['ok' => false, 'message' => 'Purchase order not found.'], 404);
        }

        $user = auth()->user();
        $issuedBy = $user ? (string) ($user->email ?? $user->username ?? $user->id) : 'system';

        try {
            $result = $this->receiveService->receive($id, $payload['items'], $issuedBy);
        } catch (RuntimeException $e) {
            return response()->json(['ok' => false, 'message' => $e->getMessage()], 409);
        } catch (\Throwable $e) {
            return response()->json(['ok' => false, 'message' => 'Unable to receive items.'], 500);
        }

        return response()->json([
            'ok' => true,
            'status' => $result['status'] ?? null,
            'completed' => $result['completed'] ?? false,
        ]);
    }

    public function cancel(int $id): JsonResponse
    {
        $po = PurchaseOrder::query()->find($id);
        if (!$po) {
            return response()->json(['ok' => false, 'message' => 'Purchase order not found.'], 404);
        }

        try {
            $this->statusService->cancel($id);
        } catch (RuntimeException $e) {
            return response()->json(['ok' => false, 'message' => $e->getMessage()], 409);
        } catch (\Throwable $e) {
            return response()->json(['ok' => false, 'message' => 'Unable to cancel purchase order.'], 500);
        }

        return response()->json(['ok' => true, 'status' => PurchaseOrder::STATUS_CANCELED]);
    }
}
