<?php

namespace App\Http\Controllers;

use App\Models\Candidate;
use App\Models\VisaInquiry;
use App\Models\Agent;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;

class MediaController extends Controller
{
    protected function serve(?string $path)
    {
        if (!$path || !Storage::disk('public')->exists($path)) {
            abort(404);
        }

        $disposition = request()->boolean('download') ? 'attachment' : 'inline';

        return response()->file(
            Storage::disk('public')->path($path),
            ['Content-Disposition' => $disposition . '; filename="' . basename($path) . '"']
        );
    }

    private function authorizeCandidateMedia(Candidate $candidate): void
    {
        $user = Auth::user();
        if (!$user) {
            abort(403);
        }

        if (method_exists($user, 'isAdmin') && $user->isAdmin()) {
            return;
        }

        if (($user->role ?? '') === 'agent') {
            $agent = Agent::where('user_id', $user->id)->first();
            if (!$agent) {
                abort(403);
            }

            if (Schema::hasColumn('candidates', 'agent_id') && (int) $candidate->agent_id !== (int) $agent->id) {
                abort(403);
            }

            if (Schema::hasTable('agent_company') && Schema::hasColumn('candidates', 'company_id')) {
                $allowedCompanyIds = $agent->allowedCompanies()->pluck('companies.id')->map(fn ($id) => (int) $id)->all();
                if (!in_array((int) $candidate->company_id, $allowedCompanyIds, true)) {
                    abort(403);
                }
            }

            return;
        }

        abort(403);
    }

    public function candidatePhoto(Candidate $candidate)
    {
        $this->authorizeCandidateMedia($candidate);
        return $this->serve($candidate->photo_path);
    }

    public function candidatePassport(Candidate $candidate)
    {
        $this->authorizeCandidateMedia($candidate);
        return $this->serve($candidate->passport_file_path);
    }

    /**
     * Visa inquiry attachments
     */
    public function visaApplicantPhoto(VisaInquiry $visaInquiry)
    {
        return $this->serve($visaInquiry->applicant_image_path);
    }

    public function visaPassportCopy(VisaInquiry $visaInquiry)
    {
        return $this->serve($visaInquiry->passport_file_path);
    }
}
