import { HttpStatus, Injectable } from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service';
import { isValidMobile, mobileSearchDigits, normalizeMobile } from '../../common/phone';
import { hasEffectivePermission } from '../../common/membership-permissions';
import { AppException, ErrorCode } from '../../common/errors';
import { CreatePatientDto } from './dto/create-patient.dto';
import { ListPatientsDto } from './dto/list-patients.dto';
import { UpdatePatientDto } from './dto/update-patient.dto';

@Injectable()
export class PatientsService {
  constructor(private readonly prisma: PrismaService) {}

  async create(createPatientDto: CreatePatientDto, organizationId: string) {
    const firstName = this.requireNonEmptyName(createPatientDto.firstName, 'firstName');
    const lastName = this.requireNonEmptyName(createPatientDto.lastName, 'lastName');
    const mobile = this.resolveMobile(createPatientDto.mobile);

    const existing = await this.prisma.patient.findUnique({
      where: { mobile },
    });

    if (existing) {
      if (
        !existing.isWalkIn &&
        existing.createdByOrganizationId === organizationId
      ) {
        return { success: true, data: existing, existing: true as const };
      }
      throw new AppException(ErrorCode.PATIENT_MOBILE_UNAVAILABLE, HttpStatus.CONFLICT);
    }

    const patient = await this.prisma.patient.create({
      data: {
        firstName,
        lastName,
        mobile,
        email: createPatientDto.email?.trim() || null,
        notes: createPatientDto.notes?.trim() || null,
        dateOfBirth: createPatientDto.dateOfBirth ? new Date(createPatientDto.dateOfBirth) : null,
        createdByOrganizationId: organizationId,
      },
    });

    return { success: true, data: patient, existing: false as const };
  }

  async findAll(query: ListPatientsDto, organizationId: string) {
    const { page = 1, limit = 10, q } = query;
    const skip = (page - 1) * limit;

    const where = {
      isWalkIn: false,
      createdByOrganizationId: organizationId,
      ...(q?.trim() ? this.buildSearchWhere(q.trim()) : {}),
    };

    const [items, total] = await Promise.all([
      this.prisma.patient.findMany({
        where,
        skip,
        take: limit,
        orderBy: [{ updatedAt: 'desc' }],
      }),
      this.prisma.patient.count({ where }),
    ]);

    return {
      success: true,
      data: {
        items,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.max(1, Math.ceil(total / limit)),
        },
      },
    };
  }

  async findOne(id: string, organizationId: string) {
    const patient = await this.findNamedPatientInOrg(id, organizationId);
    return { success: true, data: patient };
  }

  async update(id: string, updatePatientDto: UpdatePatientDto, organizationId: string) {
    await this.findNamedPatientInOrg(id, organizationId);

    const data: {
      firstName?: string;
      lastName?: string;
      mobile?: string;
      email?: string | null;
      notes?: string | null;
      dateOfBirth?: Date | null;
    } = {};

    if (updatePatientDto.firstName !== undefined) {
      data.firstName = this.requireNonEmptyName(updatePatientDto.firstName, 'firstName');
    }
    if (updatePatientDto.lastName !== undefined) {
      data.lastName = this.requireNonEmptyName(updatePatientDto.lastName, 'lastName');
    }
    if (updatePatientDto.mobile !== undefined) {
      const mobile = this.resolveMobile(updatePatientDto.mobile);
      const taken = await this.prisma.patient.findUnique({
        where: { mobile },
        select: { id: true, createdByOrganizationId: true, isWalkIn: true },
      });
      if (taken && taken.id !== id) {
        throw new AppException(ErrorCode.PATIENT_MOBILE_UNAVAILABLE, HttpStatus.CONFLICT);
      }
      data.mobile = mobile;
    }
    if (updatePatientDto.email !== undefined) {
      data.email = updatePatientDto.email?.trim() || null;
    }
    if (updatePatientDto.notes !== undefined) {
      data.notes = updatePatientDto.notes?.trim() || null;
    }
    if (updatePatientDto.dateOfBirth !== undefined) {
      data.dateOfBirth = updatePatientDto.dateOfBirth
        ? new Date(updatePatientDto.dateOfBirth)
        : null;
    }

    const updated = await this.prisma.patient.update({
      where: { id },
      data,
    });

    return { success: true, data: updated };
  }

  async listAppointments(
    patientId: string,
    organizationId: string,
    actorUserId: string,
  ) {
    await this.assertCanViewPatients(actorUserId, organizationId);
    await this.findNamedPatientInOrg(patientId, organizationId);

    const items = await this.prisma.appointment.findMany({
      where: { organizationId, patientId },
      orderBy: [{ startAt: 'desc' }],
    });

    const providerIds = [...new Set(items.map((item) => item.providerUserId))];
    const providers =
      providerIds.length === 0
        ? []
        : await this.prisma.user.findMany({
            where: { id: { in: providerIds } },
            select: { id: true, name: true },
          });
    const providerNameById = new Map(providers.map((p) => [p.id, p.name]));

    return {
      success: true,
      data: items.map((item) => ({
        id: item.id,
        startAt: item.startAt,
        endAt: item.endAt,
        purpose: item.purpose,
        providerUserId: item.providerUserId,
        providerName: providerNameById.get(item.providerUserId) ?? '',
      })),
    };
  }

  getOrganizationIdFromUser(user: { organizationId?: string }) {
    if (!user?.organizationId) {
      throw new AppException(ErrorCode.AUTH_ORG_NOT_SELECTED, HttpStatus.BAD_REQUEST);
    }
    return user.organizationId;
  }

  private buildSearchWhere(q: string) {
    const orConditions: Array<Record<string, unknown>> = [
      { firstName: { contains: q, mode: 'insensitive' as const } },
      { lastName: { contains: q, mode: 'insensitive' as const } },
      { email: { contains: q, mode: 'insensitive' as const } },
    ];

    const normalized = normalizeMobile(q);
    if (normalized) {
      orConditions.push({ mobile: normalized });
    } else {
      const digits = mobileSearchDigits(q);
      if (digits.length >= 3) {
        orConditions.push({ mobile: { contains: digits } });
      }
    }

    return { OR: orConditions };
  }

  private resolveMobile(raw: string): string {
    if (!raw?.trim()) {
      throw new AppException(ErrorCode.VALIDATION_FIELD_REQUIRED, HttpStatus.BAD_REQUEST, [
        { field: 'mobile', code: ErrorCode.VALIDATION_FIELD_REQUIRED },
      ]);
    }

    const mobile = normalizeMobile(raw);
    if (!mobile || !isValidMobile(mobile)) {
      throw new AppException(ErrorCode.VALIDATION_MOBILE_INVALID, HttpStatus.BAD_REQUEST, [
        { field: 'mobile', code: ErrorCode.VALIDATION_MOBILE_INVALID },
      ]);
    }
    return mobile;
  }

  private requireNonEmptyName(value: string, field: 'firstName' | 'lastName'): string {
    const trimmed = value?.trim() ?? '';
    if (!trimmed) {
      throw new AppException(ErrorCode.VALIDATION_FIELD_REQUIRED, HttpStatus.BAD_REQUEST, [
        { field, code: ErrorCode.VALIDATION_FIELD_REQUIRED },
      ]);
    }
    return trimmed;
  }

  private async assertCanViewPatients(userId: string, organizationId: string) {
    const membership = await this.prisma.membership.findUnique({
      where: {
        userId_organizationId: { userId, organizationId },
      },
      include: {
        organization: { include: { type: true, plan: true } },
        permissions: { include: { permission: true } },
      },
    });

    if (!membership) {
      throw new AppException(ErrorCode.PERMISSION_NOT_MEMBER, HttpStatus.FORBIDDEN);
    }

    if (!hasEffectivePermission(membership, 'TAB_PATIENTS_READ')) {
      throw new AppException(ErrorCode.PERMISSION_DENIED, HttpStatus.FORBIDDEN);
    }
  }

  private async findNamedPatientInOrg(id: string, organizationId: string) {
    const patient = await this.prisma.patient.findFirst({
      where: {
        id,
        isWalkIn: false,
        createdByOrganizationId: organizationId,
      },
    });

    if (!patient) {
      throw new AppException(ErrorCode.PATIENT_NOT_FOUND, HttpStatus.NOT_FOUND);
    }
    return patient;
  }
}
