<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use App\Services\Search\CandidateSearchService;

class CandidateSearchController extends BaseController
{
    private CandidateSearchService $search;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->search = new CandidateSearchService();
    }

    public function show(int $candidateProfileId)
    {
        $user = $this->currentUser();

        $profile = \Config\Database::connect()->table('candidate_profiles cp')
            ->select('cp.*, u.name, u.email, u.phone')
            ->join('users u', 'u.id = cp.user_id')
            ->where('cp.id', $candidateProfileId)
            ->get()->getRowArray();

        if (! $profile) {
            return $this->jsonError([['code' => 'NOT_FOUND', 'message' => 'Candidate not found.']], 404);
        }

        $unlockModel = new \App\Models\CandidateUnlockModel();
        $unlocked = $unlockModel->anyUnlockFor($user->agency_id, $candidateProfileId);
        if (! $unlocked) {
            unset($profile['email'], $profile['phone']);
        }

        (new \App\Services\Support\ActivityLogger())->log($user->id, $user->agency_id, null, 'profile_view', [
            'candidate_profile_id' => $candidateProfileId,
        ]);

        return $this->jsonSuccess(['candidate' => $profile, 'is_unlocked' => $unlocked]);
    }

    public function index()
    {
        $user = $this->currentUser();
        $filters = $this->request->getGet() ?? [];

        if (! empty($filters['skills']) && is_string($filters['skills'])) {
            $filters['skills'] = explode(',', $filters['skills']);
        }

        $page = (int) ($filters['page'] ?? 1);
        $perPage = min(50, (int) ($filters['per_page'] ?? 20));

        try {
            (new \App\Services\Billing\SubscriptionService())->assertWithinLimit($user->agency_id, 'candidate_views_used', 'candidate_view_limit');
        } catch (\App\Exceptions\PlanLimitExceededException $e) {
            return $this->jsonError([['code' => 'PLAN_LIMIT_EXCEEDED', 'message' => $e->getMessage()]], 403);
        }

        $results = $this->search->search($filters, $user->agency_id, $page, $perPage);
        (new \App\Services\Billing\SubscriptionService())->incrementUsage($user->agency_id, 'candidate_views_used');

        return $this->jsonSuccess($results, ['page' => $page, 'per_page' => $perPage]);
    }

    public function unlock(int $candidateProfileId)
    {
        $user = $this->currentUser();
        $input = $this->request->getJSON(true);

        $rules = ['type' => 'required|in_list[contact_reveal,resume_download,full_profile]'];
        if (! $this->validate($rules)) {
            return $this->jsonValidationError($this->validator->getErrors());
        }

        try {
            $result = $this->search->unlock($user->agency_id, $user->id, $candidateProfileId, $input['type']);
        } catch (\App\Exceptions\InsufficientCreditsException $e) {
            return $this->jsonError([['code' => 'INSUFFICIENT_CREDITS', 'message' => $e->getMessage()]], 402);
        }

        return $this->jsonSuccess($result);
    }

    public function save(int $candidateProfileId)
    {
        $user = $this->currentUser();
        $this->search->save($user->agency_id, $user->id, $candidateProfileId);
        return $this->jsonSuccess(['message' => 'Candidate saved.']);
    }

    public function tag(int $candidateProfileId)
    {
        $user = $this->currentUser();
        $input = $this->request->getJSON(true);

        if (empty($input['name'])) {
            return $this->jsonValidationError(['name' => 'Tag name is required.']);
        }

        $this->search->tag($user->agency_id, $candidateProfileId, $input['name'], $input['color'] ?? '#6c757d');
        return $this->jsonSuccess(['message' => 'Tag applied.']);
    }

    public function createShortlist()
    {
        $user = $this->currentUser();
        $input = $this->request->getJSON(true);

        if (empty($input['name'])) {
            return $this->jsonValidationError(['name' => 'Shortlist name is required.']);
        }

        $id = $this->search->createShortlist($user->agency_id, $user->id, $input['name'], $input['job_id'] ?? null);
        return $this->jsonSuccess(['shortlist_id' => $id], [], 201);
    }

    public function addToShortlist(int $shortlistId, int $candidateProfileId)
    {
        $this->search->addToShortlist($shortlistId, $candidateProfileId);
        return $this->jsonSuccess(['message' => 'Candidate added to shortlist.']);
    }
}
