<?php

namespace App\Modules\HR\Employees\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Employees\Models\EmployeeDocument;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class EmployeeDocumentDownloadController extends Controller
{
    public function __invoke(Employee $employee, EmployeeDocument $document): BinaryFileResponse
    {
        Gate::authorize('employees.documents.view', $employee);
        $user = request()->user();
        if ($user instanceof User && ! $user->isAdmin()) {
            abort_if($user->tenant_id === null || (int) $employee->tenant_id !== (int) $user->tenant_id, 403);
        }
        if ((int) $document->employee_id !== (int) $employee->id) {
            abort(404);
        }

        if (! Storage::disk('local')->exists($document->file_path)) {
            abort(404);
        }

        $ext = pathinfo($document->file_path, PATHINFO_EXTENSION) ?: 'bin';
        $filename = $document->type->value.'-'.$employee->employee_code.'.'.$ext;

        return Storage::disk('local')->download($document->file_path, $filename);
    }
}
