<?php

namespace App\Http\Controllers;

use App\Models\Area;
use App\Models\OrdenLavanderia;
use App\Services\LaundryTrackingPresentationService;
use Illuminate\Http\JsonResponse;

/**
 * API TIBU bajo prefijo /api/laundry (áreas, presencia por orden).
 */
class LaundryApiController extends Controller
{
    public function __construct(
        private LaundryTrackingPresentationService $trackingPresentation
    ) {
    }

    /**
     * GET /laundry/areas — áreas operativas activas.
     */
    public function areas(): JsonResponse
    {
        $this->authorize('viewAny', Area::class);

        $rows = Area::query()
            ->operational()
            ->get()
            ->map(function (Area $area) {
                return [
                    'id' => $area->id,
                    'code' => $area->code,
                    'name' => $area->name,
                    'sort_order' => $area->sort_order,
                    'requires_scan_twice' => $area->requires_scan_twice,
                    'floor_label' => $area->floor_label,
                ];
            });

        return response()->json([
            'data' => $rows,
            'meta' => null,
            'errors' => null,
        ], JsonResponse::HTTP_OK);
    }

    /**
     * GET /laundry/orders/{id}/presence — estado por área (presencia + catálogo de área).
     */
    public function orderPresence(OrdenLavanderia $orden): JsonResponse
    {
        return $this->orderLaundryStatePayload($orden);
    }

    /**
     * GET /laundry/orders/{id}/laundry-state — alias semántico del estado operativo (§20 vertical slice).
     */
    public function laundryState(OrdenLavanderia $orden): JsonResponse
    {
        return $this->orderLaundryStatePayload($orden);
    }

    private function orderLaundryStatePayload(OrdenLavanderia $orden): JsonResponse
    {
        $this->authorize('viewPresence', $orden);

        $this->trackingPresentation->loadRelationsForTracking($orden);

        $recentScans = $this->trackingPresentation->recentScansPayload($orden);

        $presences = $orden->areaPresences->map(function ($p) {
            return [
                'id' => $p->id,
                'area' => $p->area ? [
                    'id' => $p->area->id,
                    'code' => $p->area->code,
                    'name' => $p->area->name,
                ] : null,
                'status' => $p->status,
                'started_at' => $p->started_at?->toIso8601String(),
                'completed_at' => $p->completed_at?->toIso8601String(),
                'load_type_id' => $p->load_type_id,
                'load_type' => $p->loadType ? [
                    'id' => $p->loadType->id,
                    'code' => $p->loadType->code,
                    'name' => $p->loadType->name,
                ] : null,
            ];
        });

        return response()->json([
            'data' => [
                'orden_id' => $orden->id,
                'folio_unico' => $orden->folio_unico,
                'estatus' => $orden->estatus,
                'current_step' => $orden->current_step,
                'presences' => $presences,
                'recent_scans' => $recentScans,
            ],
            'meta' => null,
            'errors' => null,
        ], JsonResponse::HTTP_OK);
    }
}
