<?php

namespace App\Secretary\Controller;

use App\Auth\Entity\User;
use App\Auth\Repository\UserRepository;
use App\Clinic\Repository\ClinicRepository;
use App\Doctor\Repository\DoctorRepository;
use App\Secretary\Entity\DoctorSecretary;
use App\Secretary\Repository\DoctorSecretaryRepository;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Sms\Entity\SmsLog;
use App\Sms\Service\SmsService;
use App\Subscription\Service\SubscriptionService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use OpenApi\Attributes as OA;

#[OA\Tag(name: 'Secretaries')]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class SecretaryController extends BaseController
{
    public function __construct(
        private readonly DoctorSecretaryRepository   $secretaryRepo,
        private readonly DoctorRepository            $doctorRepo,
        private readonly ClinicRepository            $clinicRepo,
        private readonly UserRepository              $userRepo,
        private readonly UserPasswordHasherInterface $hasher,
        private readonly SubscriptionService         $subscriptionService,
        private readonly SmsService                  $smsService,
        private readonly string                      $appUrl,
    ) {}

    #[Route('/api/v1/secretary', methods: ['POST'])]
    public function create(Request $request, #[CurrentUser] User $currentUser): JsonResponse
    {
        $data       = json_decode($request->getContent(), true) ?? [];
        $doctorUuid = trim($data['doctor_uuid'] ?? '');
        $mobile     = trim($data['mobile_number'] ?? '');

        if (empty($doctorUuid) || empty($mobile)) {
            return $this->error(ErrorCodes::ERR_VALIDATION_001, 'doctor_uuid و mobile_number الزامی است', 422);
        }

        $doctor = $this->doctorRepo->findByUuid($doctorUuid);
        if ($doctor === null) {
            return $this->error(ErrorCodes::ERR_VALIDATION_002, 'دکتر یافت نشد', 404);
        }

        // تعیین scope بر اساس نقش کاربر جاری
        $ownerClinic = null;
        if ($currentUser->hasRole('ROLE_CLINIC')) {
            $ownerClinic = $this->clinicRepo->findByUser($currentUser);
            if ($ownerClinic === null || !$this->secretaryRepo->isDoctorInClinic($doctor, $ownerClinic)) {
                return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
            }
        } elseif (!$currentUser->hasRole('ROLE_ADMIN')) {
            // دکتر فقط برای خودش منشی تعریف می‌کند
            if ($doctor->getUser()->getId() !== $currentUser->getId()) {
                return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
            }
        }

        $ownerType = $ownerClinic !== null ? DoctorSecretary::OWNER_CLINIC : DoctorSecretary::OWNER_DOCTOR;

        // Check plan limit
        $limit       = $this->subscriptionService->getSecretaryLimit('doctor', $doctor->getId());
        $activeCount = $this->secretaryRepo->countActiveByDoctor($doctor);
        if ($activeCount >= $limit) {
            return $this->error(ErrorCodes::ERR_SECRETARY_001, ErrorCodes::message(ErrorCodes::ERR_SECRETARY_001), 422);
        }

        // Find or create secretary user
        $secretaryUser = $this->userRepo->findByMobile($mobile);
        if ($secretaryUser === null) {
            $secretaryUser = new User($mobile);
            if (!empty($data['password'])) {
                $hash = $this->hasher->hashPassword($secretaryUser, $data['password']);
                $secretaryUser->setPasswordHash($hash);
            }
        }
        if (!empty($data['name'])) {
            $secretaryUser->setRealName(trim($data['name']));
        }

        // Assign ROLE_SECRETARY
        $roles = $secretaryUser->getRoles();
        if (!in_array('ROLE_SECRETARY', $roles, true)) {
            $roles[] = 'ROLE_SECRETARY';
            $secretaryUser->setRoles(array_values(array_unique($roles)));
        }
        $this->userRepo->save($secretaryUser);

        // Check duplicate within same scope
        $existing = $this->secretaryRepo->findOneBy([
            'doctor'    => $doctor,
            'secretary' => $secretaryUser,
            'ownerType' => $ownerType,
        ]);
        if ($existing !== null) {
            return $this->error(ErrorCodes::ERR_VALIDATION_001, 'این منشی قبلاً اضافه شده است', 409);
        }

        $secretary = new DoctorSecretary($doctor, $secretaryUser, $ownerType, $ownerClinic);

        if (!empty($data['permissions'])) {
            $secretary->mergePermissions($data['permissions']);
        }

        $this->secretaryRepo->save($secretary);

        $this->sendWelcomeSms($mobile, $doctor, $ownerClinic);

        return $this->success(['data' => $secretary->toArray()], 201);
    }

    /** پیامک خوش‌آمد به منشی تازه‌تعریف‌شده — متن از template تگ TAG_SECRETARY */
    private function sendWelcomeSms(string $mobile, $doctor, $ownerClinic): void
    {
        $ownerName = $ownerClinic !== null
            ? ($ownerClinic->getName() ?? 'کلینیک')
            : ($doctor->getUser()->getRealName() ?? 'پزشک');

        $link = rtrim($this->appUrl, '/') . '/login';

        $this->smsService->dispatchTemplate(SmsLog::TAG_SECRETARY, $mobile, [
            'owner'    => $ownerName,
            'username' => $mobile,
            'link'     => $link,
        ]);
    }

    #[Route('/api/v1/secretary/{uuid}', methods: ['GET'])]
    public function show(string $uuid, #[CurrentUser] User $currentUser): JsonResponse
    {
        $secretary = $this->secretaryRepo->findByUuid($uuid);
        if ($secretary === null) {
            return $this->error(ErrorCodes::ERR_VALIDATION_002, 'منشی یافت نشد', 404);
        }

        if (!$this->canManage($secretary, $currentUser)) {
            return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
        }

        return $this->success(['data' => $secretary->toArray()]);
    }

    #[Route('/api/v1/secretary/{uuid}', methods: ['PATCH'])]
    public function update(string $uuid, Request $request, #[CurrentUser] User $currentUser): JsonResponse
    {
        $secretary = $this->secretaryRepo->findByUuid($uuid);
        if ($secretary === null) {
            return $this->error(ErrorCodes::ERR_VALIDATION_002, 'منشی یافت نشد', 404);
        }

        if (!$this->canManage($secretary, $currentUser)) {
            return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
        }

        $data = json_decode($request->getContent(), true) ?? [];

        if (array_key_exists('active', $data)) {
            $secretary->setActive((bool) $data['active']);
        }

        if (!empty($data['permissions'])) {
            $secretary->mergePermissions($data['permissions']);
        }

        $this->secretaryRepo->save($secretary);

        return $this->success(['data' => $secretary->toArray()]);
    }

    #[Route('/api/v1/secretary/{uuid}', methods: ['DELETE'])]
    public function deactivate(string $uuid, #[CurrentUser] User $currentUser): JsonResponse
    {
        $secretary = $this->secretaryRepo->findByUuid($uuid);
        if ($secretary === null) {
            return $this->error(ErrorCodes::ERR_VALIDATION_002, 'منشی یافت نشد', 404);
        }

        if (!$this->canManage($secretary, $currentUser)) {
            return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
        }

        $secretary->setActive(false);
        $this->secretaryRepo->save($secretary);

        return $this->success(['message' => 'منشی غیرفعال شد']);
    }

    /** لیست منشی ها مطب شخصی یک دکتر */
    #[Route('/api/v1/secretaries/{doctorUuid}', methods: ['GET'])]
    public function list(string $doctorUuid, #[CurrentUser] User $currentUser): JsonResponse
    {
        $doctor = $this->doctorRepo->findByUuid($doctorUuid);
        if ($doctor === null) {
            return $this->error(ErrorCodes::ERR_VALIDATION_002, 'دکتر یافت نشد', 404);
        }

        // فقط خود دکتر یا ادمین می‌توانند منشی ها مطب شخصی را ببینند
        if (!$currentUser->hasRole('ROLE_ADMIN') && $doctor->getUser()->getId() !== $currentUser->getId()) {
            return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
        }

        $secretaries = array_map(
            fn(DoctorSecretary $s) => $s->toArray(),
            $this->secretaryRepo->findByDoctorScope($doctor)
        );

        return $this->success($secretaries);
    }

    /** لیست همه منشی ها کلینیک (از همه دکترها، owner_type='clinic') */
    #[Route('/api/v1/secretaries/clinic/{clinicUuid}', methods: ['GET'])]
    public function listByClinic(string $clinicUuid, #[CurrentUser] User $currentUser): JsonResponse
    {
        $clinic = $this->clinicRepo->findByUuid($clinicUuid);
        if ($clinic === null) {
            return $this->error(ErrorCodes::ERR_VALIDATION_002, 'کلینیک یافت نشد', 404);
        }

        if ($clinic->getUser()->getId() !== $currentUser->getId() && !$currentUser->hasRole('ROLE_ADMIN')) {
            return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
        }

        $secretaries = array_map(
            fn(DoctorSecretary $s) => $s->toArray(),
            $this->secretaryRepo->findByClinic($clinic)
        );

        return $this->success($secretaries);
    }

    /** بررسی دسترسی برای ویرایش/حذف یک رابطه منشی — scope-aware */
    private function canManage(DoctorSecretary $secretary, User $user): bool
    {
        if ($user->hasRole('ROLE_ADMIN')) {
            return true;
        }

        if ($secretary->getOwnerType() === DoctorSecretary::OWNER_DOCTOR) {
            // فقط خود دکتر می‌تواند منشی مطب شخصی‌اش را مدیریت کند
            return $secretary->getDoctor()->getUser()->getId() === $user->getId();
        }

        if ($secretary->getOwnerType() === DoctorSecretary::OWNER_CLINIC) {
            // فقط مالک کلینیک می‌تواند منشی ها کلینیکی را مدیریت کند
            if (!$user->hasRole('ROLE_CLINIC')) {
                return false;
            }
            $clinic = $this->clinicRepo->findByUser($user);
            return $clinic !== null && $secretary->getClinic()?->getId() === $clinic->getId();
        }

        return false;
    }
}
