<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1;

use App\Enums\ExportStatus;
use App\Enums\UserRole;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreExportRequest;
use App\Http\Resources\ExportJobResource;
use App\Jobs\GenerateExportJob;
use App\Models\ExportJob;
use App\Services\BranchAccessService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;

class ExportController extends Controller
{
    public function __construct(private readonly BranchAccessService $branchAccess) {}

    public function index(Request $request): JsonResponse
    {
        $query = ExportJob::query()->orderByDesc('created_at')->limit(100);

        if ($request->user()->role !== UserRole::SuperAdmin) {
            $query->where('user_id', $request->user()->id);
        }

        return ExportJobResource::collection($query->get())->response();
    }

    public function store(StoreExportRequest $request): JsonResponse
    {
        $filters = $request->validated();
        $filters['_accessible_branch_ids'] = $this->branchAccess->accessibleBranchIds($request->user());

        $job = ExportJob::create([
            'user_id' => $request->user()->id,
            'status' => ExportStatus::Pending,
            'filters' => $filters,
        ]);

        GenerateExportJob::dispatch($job->id);

        return (new ExportJobResource($job))->response()->setStatusCode(Response::HTTP_ACCEPTED);
    }

    public function show(ExportJob $exportJob): ExportJobResource
    {
        $this->authorize('view', $exportJob);

        return new ExportJobResource($exportJob);
    }

    public function download(ExportJob $exportJob): mixed
    {
        $this->authorize('download', $exportJob);

        if ($exportJob->status !== ExportStatus::Completed || $exportJob->file_path === null) {
            return response()->json(['message' => 'Export is not ready yet.'], 409);
        }

        return Storage::disk('local')->download($exportJob->file_path, 'members-export.csv');
    }
}
