<?php

namespace App\Http\Controllers\API\Customers;

use App\Http\Controllers\Controller;
use App\Models\Document;
use App\Models\Reservation;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;

class DocumentController extends Controller
{
    /**
     * Get documents for a reservation
     */
    public function index(Request $request, int $reservationId): JsonResponse
    {
        $reservation = Reservation::findOrFail($reservationId);

        // Check if user owns this reservation
        if ($reservation->user_id !== $request->user()->id && !$request->user()->isAdmin()) {
            return response()->json([
                'message' => 'Unauthorized'
            ], 403);
        }

        $documents = Document::where('reservation_id', $reservationId)
            ->orderBy('generated_at', 'desc')
            ->get();

        return response()->json([
            'documents' => $documents->map(function ($document) {
                return [
                    'id' => $document->id,
                    'type' => $document->type,
                    'file_path' => $document->file_path,
                    'download_url' => route('api.customer.documents.download', [
                        'reservationId' => $document->reservation_id,
                        'type' => $document->type
                    ]),
                    'generated_at' => $document->generated_at->toIso8601String(),
                ];
            })
        ]);
    }

    /**
     * Download document
     */
    public function download(Request $request, int $reservationId, string $type)
    {
        $reservation = Reservation::findOrFail($reservationId);

        // Check if user owns this reservation
        if ($reservation->user_id !== $request->user()->id && !$request->user()->isAdmin()) {
            abort(403, 'Unauthorized');
        }

        $document = Document::where('reservation_id', $reservationId)
            ->where('type', $type)
            ->latest('generated_at')
            ->firstOrFail();

        if (!Storage::exists($document->file_path)) {
            abort(404, 'Document not found');
        }

        return Storage::download($document->file_path);
    }
}
