<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use App\Models\ResumeModel;
use App\Services\Candidate\ResumeUploadService;
use Config\Database;

class ResumeController extends BaseController
{
    /**
     * Streams a resume file. Access is allowed for:
     *  - the candidate who owns the resume, or
     *  - an agency user whose agency has received at least one
     *    application from that candidate WITH this exact resume attached
     *    (i.e. it was actually submitted to one of their jobs).
     * Never a directly browsable path; every request re-checks this.
     */
    public function download(int $resumeId)
    {
        $resumeModel = new ResumeModel();
        $resume = $resumeModel->find($resumeId);
        if (! $resume) {
            return $this->jsonError([['code' => 'NOT_FOUND', 'message' => 'Resume not found.']], 404);
        }

        $user = $this->currentUser();
        $db = Database::connect();

        $allowed = false;

        if ($user->isCandidate()) {
            $profile = $db->table('candidate_profiles')->where('user_id', $user->id)->get()->getRowArray();
            $allowed = $profile && (int) $profile['id'] === (int) $resume['candidate_profile_id'];
        } elseif ($user->agency_id) {
            $applicationExists = $db->table('job_applications ja')
                ->join('jobs j', 'j.id = ja.job_id')
                ->where('j.agency_id', $user->agency_id)
                ->where('ja.resume_id', $resumeId)
                ->countAllResults() > 0;
            $allowed = $applicationExists;
        }

        if (! $allowed) {
            return $this->jsonError([['code' => 'FORBIDDEN', 'message' => 'You do not have access to this resume.']], 403);
        }

        $absolutePath = (new ResumeUploadService())->absolutePath($resume['file_path']);
        if (! is_file($absolutePath)) {
            return $this->jsonError([['code' => 'FILE_MISSING', 'message' => 'The resume file is no longer available.']], 404);
        }

        return $this->response->download($absolutePath, null)->setFileName($resume['original_filename'] ?: 'resume.pdf');
    }
}
