<?php

use CodeIgniter\Router\RouteCollection;

/**
 * @var RouteCollection $routes
 */

// ============================================================================
// PUBLIC WEB ROUTES
// ============================================================================
$routes->get('/', 'Home::index');
$routes->get('/login', 'Auth::showLogin');
$routes->post('/login', 'Auth::login');
$routes->get('/register', 'Auth::showRegister');
$routes->get('/register/agency', 'Auth::showRegisterAgency');
$routes->post('/register/candidate', 'Auth::registerCandidate');
$routes->post('/register/agency', 'Auth::registerAgency');
$routes->get('/verify-account', 'Auth::showVerifyAccount');
$routes->post('/verify-account/otp', 'Auth::verifyOtp');
$routes->post('/verify-account/resend', 'Auth::resendOtp');
$routes->get('/logout', 'Auth::logout');
$routes->get('/forgot-password', 'Auth::showForgotPassword');
$routes->post('/forgot-password', 'Auth::forgotPassword');
$routes->get('/reset-password/(:segment)', 'Auth::showResetPassword/$1');
$routes->post('/reset-password/(:segment)', 'Auth::resetPassword/$1');
$routes->get('/accept-invitation/(:segment)', 'Auth::showAcceptInvitation/$1');
$routes->post('/accept-invitation/(:segment)', 'Auth::acceptInvitation/$1');
$routes->get('sitemap.xml', 'SeoController::sitemap');
$routes->get('robots.txt', 'SeoController::robots');

// --- Public LinkedIn-style profiles (candidate + agency, by username) ---
$routes->get('profile/(:segment)', 'PublicProfileController::show/$1', ['filter' => 'ratelimit:search']);
$routes->get('jobs/(:segment)', 'JobDetailController::show/$1', ['filter' => 'ratelimit:search']);
$routes->post('profile/(:segment)/reveal-contact', 'PublicProfileController::revealContact/$1', ['filter' => 'ratelimit:search']);

// ============================================================================
// INSTALLER (guarded internally by writable/install.lock check — see
// 08-installation-workflow.md)
// ============================================================================
$routes->group('install', ['namespace' => 'App\Controllers\Install', 'filter' => 'installguard'], static function ($routes) {
    $routes->get('/', 'InstallController::step1');

    $routes->get('step/1', 'InstallController::step1');
    $routes->post('step/1', 'InstallController::step1');

    $routes->get('step/2', 'InstallController::step2');
    $routes->post('step/2', 'InstallController::step2');

    $routes->get('step/3', 'InstallController::step3');
    $routes->post('step/3', 'InstallController::step3');
    $routes->post('step/3/test-connection', 'InstallController::testDatabaseConnection');

    $routes->get('step/4', 'InstallController::step4');
    $routes->post('step/4', 'InstallController::step4');

    $routes->get('step/5', 'InstallController::step5');
    $routes->post('step/5', 'InstallController::step5');

    $routes->get('step/6', 'InstallController::step6');
    $routes->post('step/6', 'InstallController::step6');
    $routes->post('step/6/test-smtp', 'InstallController::testSmtp');

    $routes->get('step/7', 'InstallController::step7');
    $routes->post('step/7', 'InstallController::step7');

    $routes->get('step/8', 'InstallController::step8');
    $routes->post('run/(:segment)', 'InstallController::runStep/$1');

    $routes->get('verify-cron', 'InstallController::verifyCron');
});

// ============================================================================
// REST API v1
// ============================================================================
$routes->group('api/v1', ['namespace' => 'App\Controllers\Api\V1'], static function ($routes) {

    // --- Auth (public) ---
    $routes->group('auth', ['namespace' => 'App\Controllers\Api\V1', 'filter' => 'ratelimit:auth'], static function ($routes) {
        $routes->post('register/candidate', 'AuthController::registerCandidate');
        $routes->post('register/agency', 'AuthController::registerAgency');
        $routes->post('login', 'AuthController::login');
        $routes->post('refresh', 'AuthController::refresh');
    });

    // --- Auth (authenticated) ---
    $routes->group('auth', ['namespace' => 'App\Controllers\Api\V1', 'filter' => 'auth'], static function ($routes) {
        $routes->post('logout', 'AuthController::logout');
        $routes->get('me', 'AuthController::me');
    });

    // --- Candidate profile (self-service, authenticated candidates only —
    // controller-level guardCandidate() double-checks role) ---
    $routes->get('resumes/(:num)/download', 'ResumeController::download/$1', ['namespace' => 'App\Controllers\Api\V1', 'filter' => 'auth']);

    $routes->group('candidates', ['namespace' => 'App\Controllers\Api\V1', 'filter' => 'auth'], static function ($routes) {
        $routes->get('me', 'CandidateController::me');
        $routes->put('me', 'CandidateController::updateMe');
        $routes->get('me/profile-views', 'ProfileViewController::myViewers');
        $routes->post('me/experience', 'CandidateController::addExperience');
        $routes->post('me/education', 'CandidateController::addEducation');
        $routes->post('me/skills', 'CandidateController::addSkill');
        $routes->delete('me/skills/(:num)', 'CandidateController::removeSkill/$1');
        $routes->post('me/resume', 'CandidateController::uploadResume');
    });

    // --- Username management (any authenticated account — candidate or agency) ---
    $routes->group('account/username', ['namespace' => 'App\Controllers\Api\V1', 'filter' => 'auth'], static function ($routes) {
        $routes->get('check', 'UsernameController::checkAvailability');
        $routes->get('suggest', 'UsernameController::suggest');
        $routes->get('status', 'UsernameController::status');
        $routes->put('/', 'UsernameController::update');
    });

    $routes->group('account/photo', ['namespace' => 'App\Controllers\Api\V1', 'filter' => 'auth'], static function ($routes) {
        $routes->post('/', 'AccountController::uploadPhoto');
        $routes->delete('/', 'AccountController::removePhoto');
    });

    // --- Agency Owner: own agency + team management ---
    // MUST be registered before the wildcard 'agencies/(:segment)' route
    // below, or CI4 matches GET agencies/me against that route first
    // (segment='me') and resolves to the public show-by-slug action.
    $routes->group('agencies/me', ['namespace' => 'App\Controllers\Api\V1', 'filter' => ['auth', 'tenant']], static function ($routes) {
        $routes->get('/', 'AgencyController::me');
        $routes->put('/', 'AgencyController::updateMe');
        $routes->post('logo', 'AgencyController::uploadLogo');
        $routes->post('cover', 'AgencyController::uploadCover');
        $routes->get('profile-views', 'ProfileViewController::myViewers');
        $routes->get('team', 'AgencyController::listTeam');
        $routes->post('team/invite', 'AgencyController::inviteRecruiter');
        $routes->delete('team/(:num)', 'AgencyController::removeRecruiter/$1');
        $routes->put('team/(:num)/permissions', 'AgencyController::setRecruiterPermission/$1');
    });

    // --- Agency public profile + reviews ---
    $routes->get('agencies/(:segment)', 'AgencyController::show/$1');
    $routes->post('agencies/(:segment)/reviews', 'AgencyController::submitReview/$1', ['filter' => 'auth']);


    // --- Public job browsing ---
    $routes->get('jobs', 'JobController::index');
    // 'mine' MUST be registered before the wildcard slug route below, or
    // CI4 matches it as jobs/(:segment) with segment='mine' first (routes
    // are matched in registration order) and resolves to
    // JobController::show('mine') instead of our intended mine() endpoint.
    $routes->get('jobs/mine', 'JobController::mine', ['filter' => ['auth', 'tenant']]);
    $routes->get('jobs/(:segment)', 'JobController::show/$1');

    // --- Agency: Job management ---
    // (See admin group note above re: route-level filter overriding group-level.)
    $routes->group('jobs', ['namespace' => 'App\Controllers\Api\V1', 'filter' => ['auth', 'tenant']], static function ($routes) {
        $routes->post('/', 'JobController::create', ['filter' => ['auth', 'tenant', 'roleguard:jobs.create']]);
        $routes->post('bulk-upload', 'JobController::bulkUpload', ['filter' => ['auth', 'tenant', 'roleguard:jobs.create']]);
        $routes->put('(:num)', 'JobController::update/$1', ['filter' => ['auth', 'tenant', 'roleguard:jobs.edit']]);
        $routes->post('(:num)/publish', 'JobController::publish/$1', ['filter' => ['auth', 'tenant', 'roleguard:jobs.publish']]);
        $routes->post('(:num)/close', 'JobController::close/$1', ['filter' => ['auth', 'tenant', 'roleguard:jobs.edit']]);
        $routes->delete('(:num)', 'JobController::delete/$1', ['filter' => ['auth', 'tenant', 'roleguard:jobs.delete']]);
    });
    // Candidates apply — deliberately OUTSIDE the tenant-scoped group above:
    // candidates never have an agency_id, so the 'tenant' filter would
    // reject them outright if this route inherited it from that group.
    $routes->post('jobs/(:num)/apply', 'ApplicationController::apply/$1', ['filter' => ['auth']]);

    // --- Candidate: own applications ---
    $routes->group('applications', ['namespace' => 'App\Controllers\Api\V1', 'filter' => 'auth'], static function ($routes) {
        $routes->get('me', 'ApplicationController::myApplications');
        $routes->get('(:num)', 'ApplicationController::show/$1');
        $routes->get('(:num)/timeline', 'ApplicationController::timeline/$1');
        $routes->post('(:num)/notes', 'ApplicationController::addNote/$1');
    });

    // --- Agency: ATS pipeline ---
    $routes->group('applications', ['namespace' => 'App\Controllers\Api\V1', 'filter' => ['auth', 'tenant', 'roleguard:applications.change_status']], static function ($routes) {
        $routes->get('kanban', 'ApplicationController::kanban');
        $routes->put('(:num)/status', 'ApplicationController::changeStatus/$1');
        $routes->post('(:num)/assign', 'ApplicationController::assign/$1', ['filter' => ['auth', 'tenant', 'roleguard:applications.assign_recruiter']]);
    });

    // --- Agency: Candidate search / talent pool ---
    $routes->group('candidates', ['namespace' => 'App\Controllers\Api\V1', 'filter' => ['auth', 'tenant', 'roleguard:candidates.search']], static function ($routes) {
        $routes->get('search', 'CandidateSearchController::index');
        $routes->get('(:num)', 'CandidateSearchController::show/$1');
        $routes->post('(:num)/unlock', 'CandidateSearchController::unlock/$1');
        $routes->post('(:num)/save', 'CandidateSearchController::save/$1');
        $routes->post('(:num)/tags', 'CandidateSearchController::tag/$1');
        $routes->post('shortlists', 'CandidateSearchController::createShortlist');
        $routes->post('shortlists/(:num)/candidates/(:num)', 'CandidateSearchController::addToShortlist/$1/$2');
    });

    // --- Billing (public: plans) ---
    $routes->get('billing/plans', 'BillingController::plans');

    // --- Billing (Agency Owner) ---
    $routes->group('billing', ['namespace' => 'App\Controllers\Api\V1', 'filter' => ['auth', 'tenant']], static function ($routes) {
        $routes->get('subscription', 'BillingController::currentSubscription');
        $routes->post('subscribe', 'BillingController::subscribe');
        $routes->get('subscription/pending-request', 'BillingController::pendingPlanRequest');
        $routes->get('credits', 'BillingController::creditBalance');
        $routes->post('credits/purchase', 'BillingController::purchaseCredits');
        $routes->get('wallet', 'BillingController::walletBalance');
        $routes->post('wallet/topup', 'BillingController::topUpWallet');
        $routes->get('invoices', 'BillingController::listInvoices');
        $routes->get('invoices/(:num)/pdf', 'BillingController::downloadInvoice/$1');
        $routes->post('refund-requests', 'BillingController::requestRefund');
    });

    // --- Connections (LinkedIn-style network) ---
    $routes->group('connections', ['namespace' => 'App\Controllers\Api\V1', 'filter' => 'auth'], static function ($routes) {
        $routes->post('/', 'ConnectionController::send');
        $routes->get('/', 'ConnectionController::myConnections');
        $routes->get('pending/received', 'ConnectionController::pendingReceived');
        $routes->get('pending/sent', 'ConnectionController::pendingSent');
        $routes->get('status/(:num)', 'ConnectionController::statusWith/$1');
        $routes->post('(:num)/accept', 'ConnectionController::accept/$1');
        $routes->post('(:num)/reject', 'ConnectionController::reject/$1');
        $routes->delete('(:num)', 'ConnectionController::remove/$1');
    });

    // --- Messaging ---
    $routes->group('conversations', ['namespace' => 'App\Controllers\Api\V1', 'filter' => 'auth'], static function ($routes) {
        $routes->get('/', 'MessagingController::index');
        $routes->post('/', 'MessagingController::start');
        $routes->get('(:num)/messages', 'MessagingController::messages/$1');
        $routes->post('(:num)/messages', 'MessagingController::send/$1');
        $routes->post('(:num)/read', 'MessagingController::markRead/$1');
    });

    // --- Interviews ---
    $routes->group('interviews', ['namespace' => 'App\Controllers\Api\V1', 'filter' => 'auth'], static function ($routes) {
        $routes->get('me', 'InterviewController::myUpcoming');
        $routes->get('agency-upcoming', 'InterviewController::agencyUpcoming', ['filter' => ['auth', 'tenant']]);
        $routes->put('(:num)', 'InterviewController::reschedule/$1');
        $routes->delete('(:num)', 'InterviewController::cancel/$1');
        $routes->post('(:num)/feedback', 'InterviewController::submitFeedback/$1');
        $routes->get('(:num)/timeline', 'InterviewController::timeline/$1');
        $routes->post('(:num)/notes', 'InterviewController::addNote/$1');
        $routes->post('(:num)/files', 'InterviewController::uploadFile/$1');
    });
    $routes->get('interview-files/(:num)/download', 'InterviewController::downloadFile/$1', ['namespace' => 'App\Controllers\Api\V1', 'filter' => 'auth']);
    $routes->post('applications/(:num)/interviews', 'InterviewController::schedule/$1', ['filter' => 'auth']);
    $routes->get('applications/(:num)/interviews', 'InterviewController::forApplication/$1', ['filter' => 'auth']);

    // --- Notifications ---
    $routes->group('notifications', ['namespace' => 'App\Controllers\Api\V1', 'filter' => 'auth'], static function ($routes) {
        $routes->get('/', 'NotificationController::index');
        $routes->post('(:num)/read', 'NotificationController::markRead/$1');
        $routes->put('preferences', 'NotificationController::updatePreferences');
    });

    // --- Admin: Agency Management (Super Admin only) ---
    $routes->group('admin/agencies', ['namespace' => 'App\Controllers\Api\V1', 'filter' => ['auth', 'roleguard:agencies.view_all']], static function ($routes) {
        $routes->get('/', 'AdminAgencyController::index');
        $routes->get('(:num)', 'AdminAgencyController::show/$1');
        $routes->post('(:num)/verify', 'AdminAgencyController::verify/$1', ['filter' => ['auth', 'roleguard:agencies.verify']]);
        $routes->post('(:num)/suspend', 'AdminAgencyController::suspend/$1', ['filter' => ['auth', 'roleguard:agencies.suspend']]);
        $routes->post('(:num)/activate', 'AdminAgencyController::activate/$1', ['filter' => ['auth', 'roleguard:agencies.suspend']]);
        $routes->post('(:num)/credits', 'AdminAgencyController::adjustCredits/$1', ['filter' => ['auth', 'roleguard:agencies.verify']]);
        $routes->get('(:num)/subscription', 'AdminAgencyController::subscriptionInfo/$1');
        $routes->post('(:num)/subscription/change-plan', 'AdminAgencyController::changeSubscriptionPlan/$1', ['filter' => ['auth', 'roleguard:agencies.verify']]);
        $routes->post('(:num)/subscription/reset-usage', 'AdminAgencyController::resetSubscriptionUsage/$1', ['filter' => ['auth', 'roleguard:agencies.verify']]);
        $routes->post('(:num)/reset-password', 'AdminAgencyController::resetPassword/$1', ['filter' => ['auth', 'roleguard:agencies.verify']]);
        $routes->get('plan-requests/pending', 'AdminAgencyController::pendingPlanRequests');
        $routes->post('plan-requests/(:num)/approve', 'AdminAgencyController::approvePlanChange/$1', ['filter' => ['auth', 'roleguard:agencies.verify']]);
        $routes->post('plan-requests/(:num)/reject', 'AdminAgencyController::rejectPlanChange/$1', ['filter' => ['auth', 'roleguard:agencies.verify']]);
    });

    // --- Admin: All Registered Users (Super Admin only) ---
    $routes->group('admin/users', ['namespace' => 'App\Controllers\Api\V1', 'filter' => ['auth', 'roleguard:settings.global']], static function ($routes) {
        $routes->get('/', 'AdminUserController::index');
        $routes->post('(:num)/suspend', 'AdminUserController::suspend/$1');
        $routes->get('(:num)/activity', 'AdminUserController::userActivity/$1');
        $routes->post('(:num)/activate', 'AdminUserController::activate/$1');
        $routes->post('(:num)/ban', 'AdminUserController::ban/$1');
    });

    // --- Settings (Super Admin only) ---
    $routes->group('settings', ['namespace' => 'App\Controllers\Api\V1', 'filter' => ['auth', 'roleguard:settings.global']], static function ($routes) {
        $routes->get('/', 'SettingsController::index');
        $routes->put('(:segment)', 'SettingsController::update/$1');
        $routes->get('credit-costs', 'SettingsController::creditCosts');
        $routes->put('credit-costs/(:segment)', 'SettingsController::updateCreditCost/$1');
        $routes->post('smtp/test', 'SettingsController::testSmtp');
    });

    // --- Admin: Payments & Refunds (Super Admin only) ---
    $routes->group('admin', ['namespace' => 'App\Controllers\Api\V1', 'filter' => ['auth', 'roleguard:settings.global']], static function ($routes) {
        $routes->get('payments', 'AdminPaymentController::index');
        $routes->get('audit-log', 'AdminAuditLogController::index');
        $routes->post('system-update/upload', 'SystemUpdateController::upload');
        $routes->get('system-update/history', 'SystemUpdateController::history');
        $routes->post('system-update/(:num)/rollback', 'SystemUpdateController::rollback/$1');
        $routes->post('payments/(:num)/verify', 'AdminPaymentController::verify/$1');
        $routes->get('refund-requests', 'AdminPaymentController::refundQueue');
        $routes->post('refund-requests/(:num)/approve', 'AdminPaymentController::approveRefund/$1');
        $routes->post('refund-requests/(:num)/reject', 'AdminPaymentController::rejectRefund/$1');
    });

    // --- Admin Reports (Super Admin only — guarded in AdminReportingService constructor) ---
    $routes->group('admin/reports', ['namespace' => 'App\Controllers\Api\V1', 'filter' => 'auth'], static function ($routes) {
        $routes->get('revenue', 'AdminReportController::revenue');
        $routes->get('subscriptions', 'AdminReportController::subscriptions');
        $routes->get('agencies', 'AdminReportController::agencies');
        $routes->get('recruiters', 'AdminReportController::recruiters');
        $routes->get('candidates', 'AdminReportController::candidates');
        $routes->get('jobs', 'AdminReportController::jobs');
        $routes->get('applications', 'AdminReportController::applications');
        $routes->get('credits', 'AdminReportController::credits');
        $routes->get('wallet', 'AdminReportController::wallet');
        $routes->get('payments', 'AdminReportController::payments');
        $routes->get('hires-by-agency', 'AdminReportController::hiresByAgency');
        $routes->get('candidate/(:num)/applications', 'AdminReportController::candidateApplications/$1');
    });

    // --- Agency Reports ---
    $routes->group('agencies/me/reports', ['namespace' => 'App\Controllers\Api\V1', 'filter' => ['auth', 'tenant', 'roleguard:reports.agency_scoped']], static function ($routes) {
        $routes->get('recruiter-performance', 'AgencyReportController::recruiterPerformance');
        $routes->get('candidate-views', 'AgencyReportController::candidateViews');
        $routes->get('contact-reveals', 'AgencyReportController::contactReveals');
        $routes->get('hires', 'AgencyReportController::hires');
        $routes->get('interviews', 'AgencyReportController::interviews');
        $routes->get('conversion-rates', 'AgencyReportController::conversionRates');
    });

    // --- Webhooks (signature-verified inside controller, no bearer auth) ---
    $routes->post('webhooks/(:segment)', 'WebhookController::handle/$1');
});

// ============================================================================
// ADMIN WEB PANEL (session auth + role guard)
// ============================================================================
$routes->group('admin', ['filter' => 'auth'], static function ($routes) {
    $routes->get('/', 'Admin\DashboardController::index', ['filter' => ['auth', 'roleguard']]);
    $routes->get('jobs', 'Panel\JobsPanelController::index');
    $routes->get('jobs/create', 'Panel\JobsPanelController::create');
    $routes->get('jobs/bulk', 'Panel\BulkJobsPanelController::index');
    $routes->get('jobs/bulk/template', 'Panel\BulkJobsPanelController::template');
    $routes->get('jobs/(:num)', 'Panel\JobsPanelController::show/$1');
    $routes->get('jobs/(:num)/edit', 'Panel\JobsPanelController::edit/$1');
    $routes->get('ats', 'Panel\AtsPanelController::index');
    $routes->get('ats/(:num)', 'Panel\AtsPanelController::detail/$1');
    $routes->get('candidates', 'Panel\CandidatesPanelController::index');
    $routes->get('profile', 'Panel\ProfilePanelController::index');
    $routes->get('applications', 'Panel\ApplicationsPanelController::index');
    $routes->get('interviews', 'Panel\InterviewsPanelController::index');
    $routes->get('notifications', 'Panel\NotificationsPanelController::index');
    $routes->get('messages', 'Panel\MessagesPanelController::index');
    $routes->get('network', 'Panel\ConnectionsPanelController::index');
    $routes->get('profile-views', 'Panel\ProfileViewsPanelController::index');
    $routes->get('team', 'Panel\TeamPanelController::index');
    $routes->get('billing', 'Panel\BillingPanelController::index');
    $routes->get('company-profile', 'Panel\CompanyPanelController::index');
    $routes->get('reports', 'Panel\ReportsPanelController::index');
    $routes->get('settings', 'Panel\SettingsPanelController::index');
    $routes->get('payments', 'Panel\PaymentsPanelController::index');
    $routes->get('audit-log', 'Panel\AuditLogPanelController::index');
    $routes->get('users', 'Panel\UsersPanelController::index');
    $routes->get('agencies', 'Admin\AgencyController::index', ['filter' => ['auth', 'roleguard:agencies.view_all']]);
    $routes->post('agencies/(:num)/verify', 'Admin\AgencyController::verify/$1', ['filter' => ['auth', 'roleguard:agencies.verify']]);
});
