<?php

namespace App\Http\Controllers\Jobs;

use App\Http\Controllers\Controller;
use App\Models\Booking;
use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Carbon;
use Throwable;

class ImportReservationController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $data = $request->validate([
            'external_reference' => ['required', 'string', 'max:191'],
        ]);

        try {
            // If you later move this to an external API, swap this line
            $booking = Booking::query()
                ->where('external_reference', $data['external_reference'])
                ->first();

            if (! $booking) {
                return response()->json([
                    'ok' => false,
                    'message' => 'Reservation not found.',
                ], 404);
            }

            $customer = $booking->customer ?? (
                isset($booking->customer_id) ? Customer::find($booking->customer_id) : null
            );

            $pickupAt = self::formatDate($booking->pickup_at ?? $booking->start_at ?? null);
            $returnAt = self::formatDate($booking->return_at ?? $booking->end_at ?? null);

            // Normalize a payload the Create form can consume
            $payload = [
                'external_reference' => $booking->external_reference,
                'source'             => $booking->source ?? 'vevs',
                'brand_id'           => $booking->brand_id ?? null,

                // Customer fields commonly needed on Job create
                'customer' => [
                    'id'    => $customer->id ?? null,
                    'name'  => $customer->name
                                ?? trim(($booking->first_name ?? '').' '.($booking->last_name ?? '')) ?: null,
                    'email' => $customer->email ?? $booking->email ?? null,
                    'phone' => $customer->phone ?? $booking->phone ?? null,
                ],

                // Reservation details
                'vehicle_id'   => $booking->vehicle_id ?? null,
                'vehicle_name' => $booking->vehicle_name ?? null,

                'pickup_at'    => $pickupAt,
                'return_at'    => $returnAt,

                'currency'      => $booking->currency ?? 'NZD',
                'total_amount'  => $booking->total_amount ?? $booking->grand_total ?? null,
                'deposit_amount'=> $booking->deposit_amount ?? null,

                'notes'        => $booking->notes ?? null,
            ];

            return response()->json(['ok' => true, 'data' => $payload], 200);

        } catch (Throwable $e) {
            report($e);
            return response()->json([
                'ok' => false,
                'message' => 'Import failed. Check logs.',
            ], 500);
        }
    }

    private static function formatDate($value): ?string
    {
        if (! $value) return null;
        $c = $value instanceof Carbon ? $value : Carbon::parse($value);
        return $c->toIso8601String();
    }
}
