import {
  BadRequestException,
  ForbiddenException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { or } from '@prisma/orm-postgres/orm-client';
import type { SafeUser } from '../auth/types/auth.types.js';
import { CompaniesService } from '../companies/companies.service.js';
import {
  normalizeOptionalEmail,
  normalizeOptionalString,
  normalizeRequiredString,
} from '../common/utils/normalize.js';
import { PrismaService } from '../prisma/prisma.service.js';
import type { AssignLeadDto } from './dto/assign-lead.dto.js';
import type { AssigneeSummaryQueryDto } from './dto/assignee-summary-query.dto.js';
import type { CreateLeadDto } from './dto/create-lead.dto.js';
import type { ListLeadsQueryDto } from './dto/list-leads-query.dto.js';
import type { UpdateLeadDto } from './dto/update-lead.dto.js';
import type { UpdateLeadStatusDto } from './dto/update-lead-status.dto.js';
import type {
  LeadAssigneeSummaryResponse,
  LeadResponse,
  LeadStatus,
  PaginatedLeadsResponse,
} from './types/lead.types.js';

const LEAD_SELECT = [
  'id',
  'firstName',
  'lastName',
  'email',
  'phone',
  'jobTitle',
  'status',
  'source',
  'notes',
  'createdById',
  'assignedToId',
  'companyId',
  'createdAt',
  'updatedAt',
] as const;

@Injectable()
export class LeadsService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly companiesService: CompaniesService,
  ) {}

  async create(
    dto: CreateLeadDto,
    currentUser: SafeUser,
  ): Promise<LeadResponse> {
    const firstName = normalizeRequiredString(dto.firstName);
    if (!firstName) {
      throw new BadRequestException('firstName is required');
    }

    const email = normalizeOptionalEmail(dto.email);
    let companyId = dto.companyId ?? null;

    if (companyId) {
      await this.ensureCompanyExists(companyId);
    } else if (email) {
      companyId = await this.companiesService.resolveCompanyIdFromEmail(email);
    }

    const lead = await this.prisma.db.orm.public.Lead.select(
      ...LEAD_SELECT,
    ).create({
      firstName,
      lastName: normalizeOptionalString(dto.lastName),
      email,
      phone: normalizeOptionalString(dto.phone),
      jobTitle: normalizeOptionalString(dto.jobTitle),
      status: dto.status ?? 'NEW',
      source: dto.source ?? 'OTHER',
      notes: normalizeOptionalString(dto.notes),
      createdById: currentUser.id,
      assignedToId: currentUser.id,
      companyId,
    });

    await this.recordActivity({
      leadId: lead.id,
      userId: currentUser.id,
      title: 'Lead created',
      description: `Lead created by ${currentUser.firstName} ${currentUser.lastName}`,
    });

    return lead;
  }

  async findAll(
    currentUser: SafeUser,
    query: ListLeadsQueryDto,
  ): Promise<PaginatedLeadsResponse> {
    const page = query.page ?? 1;
    const limit = query.limit ?? 20;
    const offset = (page - 1) * limit;

    if (
      currentUser.role === 'SALES_USER' &&
      query.assignedToId &&
      query.assignedToId !== currentUser.id
    ) {
      throw new ForbiddenException('Insufficient permissions');
    }

    // Build filtered collections using chained .where() (AND composition).
    let countQuery = this.prisma.db.orm.public.Lead;
    let listQuery = this.prisma.db.orm.public.Lead.select(...LEAD_SELECT);

    if (currentUser.role === 'SALES_USER') {
      countQuery = countQuery.where((l) =>
        l.assignedToId.eq(currentUser.id),
      ) as typeof countQuery;
      listQuery = listQuery.where((l) =>
        l.assignedToId.eq(currentUser.id),
      ) as typeof listQuery;
    }

    if (query.status) {
      const status = query.status;
      countQuery = countQuery.where((l) =>
        l.status.eq(status),
      ) as typeof countQuery;
      listQuery = listQuery.where((l) =>
        l.status.eq(status),
      ) as typeof listQuery;
    }

    if (query.source) {
      const source = query.source;
      countQuery = countQuery.where((l) =>
        l.source.eq(source),
      ) as typeof countQuery;
      listQuery = listQuery.where((l) =>
        l.source.eq(source),
      ) as typeof listQuery;
    }

    if (query.assignedToId) {
      const assignedToId = query.assignedToId;
      countQuery = countQuery.where((l) =>
        l.assignedToId.eq(assignedToId),
      ) as typeof countQuery;
      listQuery = listQuery.where((l) =>
        l.assignedToId.eq(assignedToId),
      ) as typeof listQuery;
    }

    if (query.companyId) {
      const companyId = query.companyId;
      countQuery = countQuery.where((l) =>
        l.companyId.eq(companyId),
      ) as typeof countQuery;
      listQuery = listQuery.where((l) =>
        l.companyId.eq(companyId),
      ) as typeof listQuery;
    }

    const search = query.search?.trim();
    if (search) {
      const pattern = `%${this.escapeIlikePattern(search)}%`;
      countQuery = countQuery.where((l) =>
        or(
          l.firstName.ilike(pattern),
          l.lastName.ilike(pattern),
          l.email.ilike(pattern),
          l.phone.ilike(pattern),
          l.jobTitle.ilike(pattern),
          l.notes.ilike(pattern),
        ),
      ) as typeof countQuery;
      listQuery = listQuery.where((l) =>
        or(
          l.firstName.ilike(pattern),
          l.lastName.ilike(pattern),
          l.email.ilike(pattern),
          l.phone.ilike(pattern),
          l.jobTitle.ilike(pattern),
          l.notes.ilike(pattern),
        ),
      ) as typeof listQuery;
    }

    const totalResult = await countQuery.aggregate((agg) => ({
      total: agg.count(),
    }));

    const data = await listQuery
      .orderBy((l) => l.createdAt.desc())
      .limit(limit)
      .offset(offset)
      .all();

    const total = totalResult.total;

    return {
      data,
      meta: {
        total,
        page,
        limit,
        totalPages: total === 0 ? 0 : Math.ceil(total / limit),
      },
    };
  }

  async getAssigneeSummary(
    currentUser: SafeUser,
    query: AssigneeSummaryQueryDto,
  ): Promise<LeadAssigneeSummaryResponse> {
    if (currentUser.role !== 'ADMIN') {
      throw new ForbiddenException('Insufficient permissions');
    }

    let listQuery = this.prisma.db.orm.public.Lead.select('assignedToId');

    if (query.status) {
      const status = query.status;
      listQuery = listQuery.where((l) =>
        l.status.eq(status),
      ) as typeof listQuery;
    }

    if (query.source) {
      const source = query.source;
      listQuery = listQuery.where((l) =>
        l.source.eq(source),
      ) as typeof listQuery;
    }

    if (query.companyId) {
      const companyId = query.companyId;
      listQuery = listQuery.where((l) =>
        l.companyId.eq(companyId),
      ) as typeof listQuery;
    }

    const search = query.search?.trim();
    if (search) {
      const pattern = `%${this.escapeIlikePattern(search)}%`;
      listQuery = listQuery.where((l) =>
        or(
          l.firstName.ilike(pattern),
          l.lastName.ilike(pattern),
          l.email.ilike(pattern),
          l.phone.ilike(pattern),
          l.jobTitle.ilike(pattern),
          l.notes.ilike(pattern),
        ),
      ) as typeof listQuery;
    }

    const rows = await listQuery.all();
    const counts = new Map<string, number>();

    for (const row of rows) {
      const userId = row.assignedToId;
      counts.set(userId, (counts.get(userId) || 0) + 1);
    }

    return {
      total: rows.length,
      assignees: Array.from(counts.entries()).map(([userId, count]) => ({
        userId,
        count,
      })),
    };
  }

  async findOne(id: string, currentUser: SafeUser): Promise<LeadResponse> {
    const lead = await this.prisma.db.orm.public.Lead.select(...LEAD_SELECT)
      .where((l) => l.id.eq(id))
      .first();

    if (!lead) {
      throw new NotFoundException('Lead not found');
    }

    this.assertCanAccessLead(lead, currentUser);
    return lead;
  }

  async update(
    id: string,
    dto: UpdateLeadDto,
    currentUser: SafeUser,
  ): Promise<LeadResponse> {
    const existing = await this.getLeadOrThrow(id);
    this.assertCanManageLead(existing, currentUser);

    if (dto.companyId) {
      await this.ensureCompanyExists(dto.companyId);
    }

    const data: {
      firstName?: string;
      lastName?: string | null;
      email?: string | null;
      phone?: string | null;
      jobTitle?: string | null;
      source?: LeadResponse['source'];
      notes?: string | null;
      companyId?: string | null;
    } = {};

    if (dto.firstName !== undefined) {
      const firstName = normalizeRequiredString(dto.firstName);
      if (!firstName) {
        throw new BadRequestException('firstName cannot be empty');
      }
      data.firstName = firstName;
    }
    if (dto.lastName !== undefined) {
      data.lastName = normalizeOptionalString(dto.lastName);
    }
    if (dto.email !== undefined) {
      data.email = normalizeOptionalEmail(dto.email);
    }
    if (dto.phone !== undefined) {
      data.phone = normalizeOptionalString(dto.phone);
    }
    if (dto.jobTitle !== undefined) {
      data.jobTitle = normalizeOptionalString(dto.jobTitle);
    }
    if (dto.source !== undefined) {
      data.source = dto.source;
    }
    if (dto.notes !== undefined) {
      data.notes = normalizeOptionalString(dto.notes);
    }
    if (dto.companyId !== undefined) {
      data.companyId = dto.companyId;
    }

    if (Object.keys(data).length === 0) {
      return this.findOne(id, currentUser);
    }

    const updated = await this.prisma.db.orm.public.Lead.select(...LEAD_SELECT)
      .where((l) => l.id.eq(id))
      .update(data);

    const lead = Array.isArray(updated) ? updated[0] : updated;
    if (!lead) {
      throw new NotFoundException('Lead not found');
    }

    return lead;
  }

  async updateStatus(
    id: string,
    dto: UpdateLeadStatusDto,
    currentUser: SafeUser,
  ): Promise<LeadResponse> {
    const existing = await this.getLeadOrThrow(id);
    this.assertCanManageLead(existing, currentUser);

    if (existing.status === dto.status) {
      return this.findOne(id, currentUser);
    }

    const updated = await this.prisma.db.orm.public.Lead.select(...LEAD_SELECT)
      .where((l) => l.id.eq(id))
      .update({ status: dto.status });

    await this.recordActivity({
      leadId: id,
      userId: currentUser.id,
      title: 'Lead status changed',
      description: `Status changed from ${existing.status} to ${dto.status}`,
    });

    const lead = Array.isArray(updated) ? updated[0] : updated;
    if (!lead) {
      throw new NotFoundException('Lead not found');
    }

    return lead;
  }

  async assign(
    id: string,
    dto: AssignLeadDto,
    currentUser: SafeUser,
  ): Promise<LeadResponse> {
    const existing = await this.getLeadOrThrow(id);
    this.assertCanAssignLead(existing, currentUser);

    if (existing.assignedToId === dto.assignedToId) {
      return this.findOne(id, currentUser);
    }

    const nextAssignee = await this.ensureActiveUserExists(dto.assignedToId);
    const previousLabel = await this.getUserDisplayName(existing.assignedToId);
    const nextLabel = this.formatUserDisplayName(nextAssignee);

    const updated = await this.prisma.db.orm.public.Lead.select(...LEAD_SELECT)
      .where((l) => l.id.eq(id))
      .update({ assignedToId: dto.assignedToId });

    await this.recordActivity({
      leadId: id,
      userId: currentUser.id,
      title: 'Lead reassigned',
      description: `Lead reassigned from ${previousLabel} to ${nextLabel}`,
    });

    const lead = Array.isArray(updated) ? updated[0] : updated;
    if (!lead) {
      throw new NotFoundException('Lead not found');
    }

    return lead;
  }

  async remove(id: string): Promise<void> {
    await this.getLeadOrThrow(id);
    await this.prisma.db.orm.public.Lead.where((lead) =>
      lead.id.eq(id),
    ).delete();
  }

  private async recordActivity(input: {
    leadId: string;
    userId: string;
    title: string;
    description: string;
  }): Promise<void> {
    await this.prisma.db.orm.public.Activity.create({
      type: 'NOTE',
      title: input.title,
      description: input.description,
      leadId: input.leadId,
      userId: input.userId,
    });
  }

  private async getLeadOrThrow(id: string): Promise<{
    id: string;
    status: LeadStatus;
    assignedToId: string;
    createdById: string;
  }> {
    const lead = await this.prisma.db.orm.public.Lead.select(
      'id',
      'status',
      'assignedToId',
      'createdById',
    )
      .where((l) => l.id.eq(id))
      .first();

    if (!lead) {
      throw new NotFoundException('Lead not found');
    }

    return lead;
  }

  private assertCanAccessLead(
    lead: { assignedToId: string },
    currentUser: SafeUser,
  ): void {
    if (
      currentUser.role === 'SALES_USER' &&
      lead.assignedToId !== currentUser.id
    ) {
      throw new ForbiddenException('Insufficient permissions');
    }
  }

  private assertCanManageLead(
    lead: { assignedToId: string },
    currentUser: SafeUser,
  ): void {
    this.assertCanAccessLead(lead, currentUser);
  }

  private assertCanAssignLead(
    lead: { assignedToId: string },
    currentUser: SafeUser,
  ): void {
    if (currentUser.role === 'ADMIN') {
      return;
    }

    if (lead.assignedToId === currentUser.id) {
      return;
    }

    throw new ForbiddenException('Insufficient permissions');
  }

  private async ensureCompanyExists(companyId: string): Promise<void> {
    const company = await this.prisma.db.orm.public.Company.select('id')
      .where((c) => c.id.eq(companyId))
      .first();

    if (!company) {
      throw new NotFoundException('Company not found');
    }
  }

  private async ensureActiveUserExists(userId: string): Promise<{
    id: string;
    firstName: string;
    lastName: string | null;
    email: string;
    isActive: boolean;
  }> {
    const user = await this.prisma.db.orm.public.User.select(
      'id',
      'firstName',
      'lastName',
      'email',
      'isActive',
    )
      .where((u) => u.id.eq(userId))
      .first();

    if (!user) {
      throw new NotFoundException('Assignee not found');
    }

    if (!user.isActive) {
      throw new BadRequestException('Assignee is inactive');
    }

    return user;
  }

  private async getUserDisplayName(userId: string | null): Promise<string> {
    if (!userId) return 'Unassigned';

    const user = await this.prisma.db.orm.public.User.select(
      'firstName',
      'lastName',
      'email',
    )
      .where((u) => u.id.eq(userId))
      .first();

    if (!user) return 'Unknown user';
    return this.formatUserDisplayName(user);
  }

  private formatUserDisplayName(user: {
    firstName: string;
    lastName: string | null;
    email?: string | null;
  }): string {
    const name = [user.firstName, user.lastName].filter(Boolean).join(' ').trim();
    return name || user.email || 'Unknown user';
  }

  private escapeIlikePattern(value: string): string {
    return value.replace(/[\\%_]/g, '\\$&');
  }
}
