<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Application;
use App\Models\User;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ApplicantExportController extends Controller
{
    public function applicants(Request $request): StreamedResponse
    {
        $this->authorizeAdmin($request);

        return response()->streamDownload(function (): void {
            $handle = fopen('php://output', 'w');

            fputcsv($handle, [
                'Applicant ID',
                'Name',
                'Email',
                'Username',
                'Joined At',
                'Questionnaire Completed At',
                'Access Unlocked At',
                'Resume Uploaded At',
                'Resume Analyzed At',
                'Profile Completed At',
                'ATS Score',
                'Remote Readiness Score',
                'Resume Filename',
                'Resume Disk',
                'Resume Path',
                'Profile Headline',
                'Current Role',
                'Experience Level',
                'Preferred Categories',
                'Preferred Roles',
                'Skills',
                'Saved Jobs',
                'Applications',
                'Viewed/Interested Jobs',
                'Last Login At',
            ]);

            User::query()
                ->where('role', 'user')
                ->withCount(['savedJobs', 'applications', 'jobInterests'])
                ->with(['profile', 'resumeReport'])
                ->orderBy('id')
                ->chunkById(200, function ($users) use ($handle): void {
                    foreach ($users as $user) {
                        fputcsv($handle, [
                            $user->id,
                            $user->name,
                            $user->email,
                            $user->username,
                            $user->created_at?->toDateTimeString(),
                            $user->questionnaire_completed_at?->toDateTimeString(),
                            $user->access_unlocked_at?->toDateTimeString(),
                            $user->resume_uploaded_at?->toDateTimeString(),
                            $user->resume_analyzed_at?->toDateTimeString(),
                            $user->profile_completed_at?->toDateTimeString(),
                            $user->resumeReport?->ats_score,
                            $user->resumeReport?->remote_readiness_score,
                            $user->resumeReport?->original_filename,
                            $user->resumeReport?->disk,
                            $user->resumeReport?->path,
                            $user->profile?->headline,
                            $user->profile?->current_role,
                            $user->profile?->experience_level,
                            implode(', ', $user->profile?->preferred_categories ?? []),
                            implode(', ', $user->profile?->preferred_roles ?? []),
                            implode(', ', $user->profile?->skills ?? []),
                            $user->saved_jobs_count,
                            $user->applications_count,
                            $user->job_interests_count,
                            $user->last_login_at?->toDateTimeString(),
                        ]);
                    }
                });

            fclose($handle);
        }, 'remotematch-applicants-'.now()->format('Y-m-d-His').'.csv', [
            'Content-Type' => 'text/csv; charset=UTF-8',
        ]);
    }

    public function applications(Request $request): StreamedResponse
    {
        $this->authorizeAdmin($request);

        return response()->streamDownload(function (): void {
            $handle = fopen('php://output', 'w');

            fputcsv($handle, [
                'Application ID',
                'Applicant ID',
                'Applicant Name',
                'Applicant Email',
                'Job ID',
                'Job Title',
                'Company',
                'Category',
                'Source',
                'Status',
                'Applied At',
                'Follow Up At',
                'Notes',
                'Source Attribution',
            ]);

            Application::query()
                ->with(['user', 'importedJob', 'source'])
                ->orderBy('id')
                ->chunkById(200, function ($applications) use ($handle): void {
                    foreach ($applications as $application) {
                        fputcsv($handle, [
                            $application->id,
                            $application->user_id,
                            $application->user?->name,
                            $application->user?->email,
                            $application->imported_job_id,
                            $application->importedJob?->title,
                            $application->importedJob?->company,
                            $application->importedJob?->category,
                            $application->source?->name,
                            $application->status,
                            $application->applied_at?->toDateTimeString(),
                            $application->follow_up_at?->toDateString(),
                            $application->notes,
                            $application->source_attribution,
                        ]);
                    }
                });

            fclose($handle);
        }, 'remotematch-applications-'.now()->format('Y-m-d-His').'.csv', [
            'Content-Type' => 'text/csv; charset=UTF-8',
        ]);
    }

    private function authorizeAdmin(Request $request): void
    {
        abort_unless($request->user('admin')?->isAdmin(), 403);
    }
}
