<?php

namespace App\Modules\Exports\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Exports\Models\Export;
use App\Modules\Exports\Repositories\ExportRepository;
use App\Modules\Exports\Requests\StoreExportRequest;
use App\Modules\Exports\Services\ExportManagerService;
use App\Modules\Exports\Support\ExportStatus;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class ExportCenterController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        private readonly ExportRepository $exports,
        private readonly ExportManagerService $manager,
    ) {}

    public function index(): View
    {
        $this->authorize('viewAny', Export::class);
        $tenant = $this->tenant();
        $paginator = $this->exports->paginateForTenant((int) $tenant->id);

        return view('pages.exports.index', compact('paginator'));
    }

    public function store(StoreExportRequest $request): RedirectResponse
    {
        $this->authorize('create', Export::class);
        $filters = $request->validated('filters');
        $this->manager->request($request->user(), (string) $request->validated('type'), $filters);

        return redirect()->route('exports.index')->with('status', __('exports.flash.queued'));
    }

    public function download(int $export)
    {
        $tenant = $this->tenant();
        $row = $this->exports->findForTenant((int) $tenant->id, $export);
        abort_if($row === null, 404);
        $this->authorize('download', $row);
        if ($row->status !== ExportStatus::COMPLETED || $row->file_path === null) {
            return redirect()->route('exports.index')->with('status', __('exports.flash.not_ready'));
        }

        return Storage::disk('local')->download($row->file_path, $row->file_name ?? 'export.csv');
    }

    private function tenant(): Tenant
    {
        $t = auth()->user()?->tenant;
        abort_if($t === null, 403);

        return $t;
    }
}
