<?php

namespace App\Http\Controllers;

use App\Exports\StaffProductivityExport;
use App\Models\User;
use App\Services\Users\StaffProductivityService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class StaffProductivityExportController extends Controller
{
    public function __invoke(Request $request, StaffProductivityService $service): BinaryFileResponse
    {
        Gate::authorize('viewAny', User::class);

        $from = $request->query('from');
        $to = $request->query('to');
        $from = is_string($from) && trim($from) !== '' ? trim($from) : null;
        $to = is_string($to) && trim($to) !== '' ? trim($to) : null;

        if ($service->resolveFilterBounds($from, $to) === false) {
            abort(422, 'Rango de fechas inválido.');
        }

        $filename = 'productividad-personal-'.now()->format('Y-m-d-His').'.xlsx';
        $tempPath = storage_path('app/tmp/exports/'.uniqid('staff_productivity_', true).'.xlsx');

        (new StaffProductivityExport($service, $from, $to))->saveTo($tempPath);

        return response()->download($tempPath, $filename, [
            'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        ])->deleteFileAfterSend(true);
    }
}
