<?php

namespace App\Modules\HR\Recruitment\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Recruitment\Models\RecruitmentCandidate;
use App\Modules\HR\Recruitment\Models\RecruitmentCandidateCv;
use App\Modules\HR\Recruitment\Repositories\RecruitmentCandidateCvRepository;
use App\Modules\HR\Recruitment\Repositories\RecruitmentCandidateRepository;
use App\Modules\HR\Recruitment\Requests\StoreCandidateCvRequest;
use App\Modules\HR\Recruitment\Services\RecruitmentCandidateCvService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Illuminate\View\View;

class CandidateCvsPageController extends Controller
{
    public function __construct(
        private readonly RecruitmentCandidateCvService $service,
        private readonly RecruitmentCandidateCvRepository $repository,
        private readonly RecruitmentCandidateRepository $candidates,
    ) {}

    public function index(Request $request): View
    {
        $this->authorize('viewAny', RecruitmentCandidateCv::class);
        $tenantId = $this->tenantId();

        return view('pages.hr.recruitment.cvs.index', [
            'cvs' => $this->repository->paginateForTenant($tenantId, [
                'q' => $request->string('q')->toString() ?: null,
                'candidate_id' => $request->integer('candidate_id') ?: null,
            ]),
            'candidateOptions' => collect($this->candidates->searchForLookup($tenantId, '', 50))
                ->mapWithKeys(fn ($o) => [$o['value'] => $o['label']])
                ->all(),
        ]);
    }

    public function store(StoreCandidateCvRequest $request): RedirectResponse
    {
        $candidate = RecruitmentCandidate::query()->findOrFail((int) $request->validated('candidate_id'));
        $this->authorize('create', RecruitmentCandidateCv::class);

        $this->service->store(
            $candidate,
            $request->file('file'),
            (int) $request->user()->id,
            (bool) ($request->validated('is_primary') ?? false),
            $request->validated('notes'),
        );

        $redirect = $request->headers->get('referer')
            ?: route('hr.recruitment.cvs.index');

        return redirect($redirect)->with('status', __('recruitment.cvs.flash.uploaded'));
    }

    public function download(RecruitmentCandidateCv $cv): StreamedResponse
    {
        $this->authorize('view', $cv);
        abort_unless(Storage::disk('local')->exists($cv->file_path), 404);

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

    public function destroy(RecruitmentCandidateCv $cv): RedirectResponse
    {
        $this->authorize('delete', $cv);
        $this->service->destroy($cv);

        return redirect()
            ->back()
            ->with('status', __('recruitment.cvs.flash.deleted'));
    }

    private function tenantId(): int
    {
        $id = auth()->user()?->tenant_id;
        abort_if($id === null, 403);

        return (int) $id;
    }
}
