import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { DealStage, Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { assertCanDelete, assertTenantOwner, createEntityNote, listEntityNotes, rethrowRelationConflict, type CrmActor } from '../../common/crm/crm-record.helper';
import { CreateNoteDto } from '../../common/dto/create-note.dto';
import { NumberingService } from '../numbering/numbering.service';
import { type CustomerView } from './customer.constants';
import { CreateCustomerDto } from './dto/create-customer.dto';
import { UpdateCustomerDto } from './dto/update-customer.dto';
import { ListCustomersQuery } from './dto/list-customers.query';

const NOT_FOUND = 'Customer not found';
const OPEN_STAGES: DealStage[] = [DealStage.QUALIFICATION, DealStage.NEEDS_ANALYSIS, DealStage.PROPOSAL, DealStage.NEGOTIATION];

const customerSelect = {
  id: true,
  customerNumber: true,
  name: true,
  industry: true,
  city: true,
  website: true,
  phone: true,
  techStack: true,
  createdAt: true,
  updatedAt: true,
  owner: { select: { id: true, name: true } },
  deals: {
    select: { id: true, stage: true, amount: true },
  },
  contacts: {
    select: { id: true, name: true, email: true, phone: true, title: true, lifecycle: true },
    orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
  },
  _count: {
    select: { contacts: true },
  },
} satisfies Prisma.CustomerSelect;

type CustomerRow = Prisma.CustomerGetPayload<{ select: typeof customerSelect }>;

export type CustomerDto = Omit<CustomerRow, 'deals'> & {
  contactPerson: string | null;
  email: string | null;
  contactTitle: string | null;
  contactsCount: number;
  openPipeline: number;
  openDealsCount: number;
  wonToDate: number;
};

export type CustomerCounts = Record<CustomerView, number>;

/** What deleting a customer would remove, and what blocks it. */
export interface CustomerDeleteCheck {
  canDelete: boolean;
  blockers: { deals: number; projects: number; quotes: number; invoices: number };
  willDelete: { contacts: number; notes: number; tasks: number; files: number };
  reason: string | null;
}

type PrimaryContactInput = { contactPerson?: string | null; email?: string | null; contactTitle?: string | null; phone?: string | null };

export type CustomerFilters = Partial<Pick<ListCustomersQuery, 'view' | 'industry' | 'city' | 'ownerId' | 'createdFrom' | 'createdTo' | 'q'>>;

@Injectable()
export class CustomersService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly tenant: TenantQueryHelper,
    private readonly numbering: NumberingService,
  ) {}

  // Builds tenant-scoped query filter for customer tab views.
  private viewWhere(view: CustomerView, userId: string): Prisma.CustomerWhereInput {
    return view === 'mine' ? { ownerId: userId } : {};
  }

  // Maps database customer record and aggregated deal statistics to CustomerDto.
  private toDto(row: CustomerRow): CustomerDto {
    const { deals, ...rest } = row;
    let openPipeline = 0;
    let openDealsCount = 0;
    let wonToDate = 0;
    for (const d of deals) {
      const amt = Number(d.amount);
      if (OPEN_STAGES.includes(d.stage)) {
        openPipeline += amt;
        openDealsCount += 1;
      } else if (d.stage === DealStage.CLOSED_WON) {
        wonToDate += amt;
      }
    }
    const primaryContact = row.contacts[0];
    return {
      ...rest,
      phone: row.phone || primaryContact?.phone || null,
      contactPerson: primaryContact?.name ?? null,
      email: primaryContact?.email || null,
      contactTitle: primaryContact?.title ?? null,
      contactsCount: row._count.contacts,
      openPipeline,
      openDealsCount,
      wonToDate,
    };
  }

  // Finds a customer within tenant scope or throws NotFoundException.
  private async findOrThrow(ctx: RequestTenantContext, id: string) {
    const row = await this.prisma.customer.findFirst({
      where: this.tenant.scopeWhere(ctx, { id }),
      select: { id: true, name: true },
    });
    if (!row) throw new NotFoundException(NOT_FOUND);
    return row;
  }

  /** Creates a customer row with the next CUST number inside the caller's transaction (used by create and lead conversion). */
  async createInTransaction(tx: Prisma.TransactionClient, ctx: RequestTenantContext, data: { name: string; city?: string | null; phone?: string | null; industry?: string | null; website?: string | null; techStack?: string | null; ownerId: string | null }) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const customerNumber = await this.numbering.getNextNumber(tenantId, 'CUSTOMER', 'GLOBAL', tx);
    return tx.customer.create({
      data: this.tenant.scopeCreate(ctx, { ...data, customerNumber }),
      select: { id: true, name: true, customerNumber: true },
    });
  }

  /** Creates or updates the customer's primary (earliest) contact from the form's contact fields. */
  private async savePrimaryContact(tx: Prisma.TransactionClient, ctx: RequestTenantContext, accountId: string, fallbackName: string, ownerId: string | null | undefined, input: PrimaryContactInput) {
    const touched = input.contactPerson !== undefined || input.email !== undefined || input.contactTitle !== undefined;
    if (!touched) return;
    const primary = await tx.contact.findFirst({
      where: this.tenant.scopeWhere(ctx, { accountId }),
      orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
      select: { id: true },
    });
    if (primary) {
      await tx.contact.updateMany({
        where: this.tenant.scopeWhere(ctx, { id: primary.id }),
        data: {
          ...(input.contactPerson ? { name: input.contactPerson } : {}),
          ...(input.email !== undefined ? { email: input.email ?? '' } : {}),
          ...(input.contactTitle !== undefined ? { title: input.contactTitle } : {}),
        },
      });
      return;
    }
    if (!input.contactPerson && !input.email) return;
    await tx.contact.create({
      data: this.tenant.scopeCreate(ctx, {
        accountId,
        name: input.contactPerson || fallbackName,
        email: input.email ?? '',
        title: input.contactTitle ?? null,
        phone: input.phone ?? null,
        ownerId: ownerId ?? null,
        lifecycle: 'Customer',
      }),
    });
  }

  // Returns customer counts for all preset views within tenant scope.
  async counts(ctx: RequestTenantContext): Promise<CustomerCounts> {
    const [all, mine] = await Promise.all([this.prisma.customer.count({ where: this.tenant.scopeWhere(ctx) }), this.prisma.customer.count({ where: this.tenant.scopeWhere(ctx, this.viewWhere('mine', ctx.userId)) })]);
    return { all, mine };
  }

  // Returns lightweight customer options for dropdown selectors.
  async options(ctx: RequestTenantContext) {
    return this.prisma.customer.findMany({
      where: this.tenant.scopeWhere(ctx),
      orderBy: [{ name: 'asc' }],
      select: { id: true, name: true, city: true, customerNumber: true },
    });
  }

  // Checks for existing duplicate customers matching name or website.
  async checkDuplicate(ctx: RequestTenantContext, name?: string, website?: string, excludeId?: string) {
    const cleanName = name?.trim();
    const cleanWeb = website
      ?.trim()
      .replace(/^https?:\/\//i, '')
      .replace(/^www\./i, '')
      .replace(/\/.*$/, '')
      .toLowerCase();
    if (!cleanName && !cleanWeb) return [];

    const orClauses: Prisma.CustomerWhereInput[] = [];
    if (cleanName) orClauses.push({ name: cleanName });
    if (cleanWeb) orClauses.push({ website: { contains: cleanWeb } });

    return this.prisma.customer.findMany({
      where: this.tenant.scopeWhere(ctx, {
        ...(excludeId ? { id: { not: excludeId } } : {}),
        OR: orClauses,
      }),
      take: 5,
      select: { id: true, name: true, city: true, website: true, customerNumber: true },
    });
  }

  /** Builds the tenant-scoped customer filter shared by the list and the export. */
  filterWhere(ctx: RequestTenantContext, q: CustomerFilters): Prisma.CustomerWhereInput {
    const term = q.q;
    let dateWhere: Prisma.CustomerWhereInput = {};
    if (q.createdFrom || q.createdTo) {
      dateWhere = {
        createdAt: {
          ...(q.createdFrom ? { gte: new Date(q.createdFrom) } : {}),
          ...(q.createdTo ? { lte: new Date(q.createdTo) } : {}),
        },
      };
    }

    return this.tenant.scopeWhere(ctx, {
      AND: [
        this.viewWhere(q.view ?? 'all', ctx.userId),
        q.industry ? { industry: { contains: q.industry } } : {},
        q.city ? { city: q.city } : {},
        q.ownerId ? { ownerId: q.ownerId } : {},
        dateWhere,
        term
          ? {
              OR: [{ name: { contains: term } }, { customerNumber: { contains: term } }, { city: { contains: term } }, { industry: { contains: term } }, { website: { contains: term } }, { techStack: { contains: term } }, { phone: { contains: term } }, { contacts: { some: { OR: [{ name: { contains: term } }, { email: { contains: term } }] } } }],
            }
          : {},
      ],
    } satisfies Prisma.CustomerWhereInput);
  }

  // Returns paginated customers matching filters, search queries, and sorting.
  async list(ctx: RequestTenantContext, q: ListCustomersQuery) {
    const where = this.filterWhere(ctx, q);

    const orderBy: Prisma.CustomerOrderByWithRelationInput[] = [q.sort === 'owner' ? { owner: { name: q.dir } } : { [q.sort]: q.dir }, { id: 'asc' }];

    const [total, rows, counts, cityRows] = await Promise.all([
      this.prisma.customer.count({ where }),
      this.prisma.customer.findMany({
        where,
        orderBy,
        skip: (q.page - 1) * q.pageSize,
        take: q.pageSize,
        select: customerSelect,
      }),
      this.counts(ctx),
      this.prisma.customer.findMany({
        where: this.tenant.scopeWhere(ctx, { city: { not: null } }),
        distinct: ['city'],
        select: { city: true },
        orderBy: { city: 'asc' },
      }),
    ]);

    return {
      items: rows.map((r) => this.toDto(r)),
      total,
      page: q.page,
      pageSize: q.pageSize,
      counts,
      cities: cityRows.map((c) => c.city).filter((c): c is string => Boolean(c && c.trim())),
    };
  }

  // Retrieves a single customer by ID including contacts and deals.
  async get(ctx: RequestTenantContext, id: string) {
    const row = await this.prisma.customer.findFirst({
      where: this.tenant.scopeWhere(ctx, { id }),
      select: {
        ...customerSelect,
        deals: {
          orderBy: [{ createdAt: 'desc' }],
          select: { id: true, dealNumber: true, title: true, stage: true, amount: true },
        },
        projects: {
          orderBy: [{ createdAt: 'desc' }],
          select: {
            id: true,
            projectNumber: true,
            name: true,
            status: true,
            startDate: true,
            targetEndDate: true,
            budgetAmount: true,
            owner: { select: { id: true, name: true } },
          },
        },
      },
    });
    if (!row) throw new NotFoundException(NOT_FOUND);
    return {
      ...this.toDto(row),
      contacts: row.contacts,
      deals: row.deals.map((d) => ({ ...d, amount: Number(d.amount) })),
      projects: ((row as any).projects || []).map((p: any) => ({
        ...p,
        budgetAmount: Number(p.budgetAmount),
        startDate: p.startDate?.toISOString() || null,
        targetEndDate: p.targetEndDate?.toISOString() || null,
      })),
    };
  }

  // Creates a new customer and its primary contact in one transaction.
  async create(ctx: RequestTenantContext, dto: CreateCustomerDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const ownerId = dto.ownerId === undefined ? ctx.userId : dto.ownerId;
    await assertTenantOwner(this.prisma, tenantId, ownerId);
    const { contactPerson, email, contactTitle, ...accountData } = dto;
    const created = await this.prisma.$transaction(async (tx) => {
      const account = await this.createInTransaction(tx, ctx, { ...accountData, ownerId });
      await this.savePrimaryContact(tx, ctx, account.id, account.name, ownerId, { contactPerson, email, contactTitle, phone: dto.phone });
      return account;
    });
    return this.get(ctx, created.id);
  }

  // Updates a customer's details and its primary contact in one transaction.
  async update(ctx: RequestTenantContext, id: string, dto: UpdateCustomerDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const account = await this.findOrThrow(ctx, id);
    await assertTenantOwner(this.prisma, tenantId, dto.ownerId);
    const { contactPerson, email, contactTitle, ...accountData } = dto;
    await this.prisma.$transaction(async (tx) => {
      await tx.customer.updateMany({ where: this.tenant.scopeWhere(ctx, { id }), data: accountData });
      await this.savePrimaryContact(tx, ctx, id, dto.name ?? account.name, dto.ownerId, { contactPerson, email, contactTitle, phone: dto.phone });
    });
    return this.get(ctx, id);
  }

  // Reports what deleting a customer would remove and whether business records block it.
  async deleteCheck(ctx: RequestTenantContext, id: string): Promise<CustomerDeleteCheck> {
    const account = await this.findOrThrow(ctx, id);
    const contactIds = (await this.prisma.contact.findMany({ where: this.tenant.scopeWhere(ctx, { accountId: id }), select: { id: true } })).map((c) => c.id);
    const linked = (field: 'accountId' | 'contactId') => this.tenant.scopeWhere(ctx, { OR: [{ accountId: id }, ...(contactIds.length ? [{ [field]: { in: contactIds } }] : [])] });
    const [deals, projects, quotes, invoices, notes, tasks, files] = await Promise.all([
      this.prisma.deal.count({ where: linked('contactId') }),
      this.prisma.project.count({ where: this.tenant.scopeWhere(ctx, { accountId: id }) }),
      this.prisma.quote.count({ where: linked('contactId') }),
      this.prisma.invoice.count({ where: linked('contactId') }),
      this.prisma.activity.count({ where: linked('contactId') }),
      this.prisma.task.count({ where: linked('contactId') }),
      this.prisma.file.count({ where: linked('contactId') }),
    ]);
    const blockers = { deals, projects, quotes, invoices };
    const parts = (Object.entries(blockers) as Array<[string, number]>).filter(([, n]) => n > 0).map(([k, n]) => `${n} ${n === 1 ? k.slice(0, -1) : k}`);
    return {
      canDelete: parts.length === 0,
      blockers,
      willDelete: { contacts: contactIds.length, notes, tasks, files },
      reason: parts.length ? `"${account.name}" has ${parts.join(', ')}. Delete or move them first.` : null,
    };
  }

  // Deletes a customer with its contacts, notes, tasks and files when no deals, projects, quotes or invoices exist.
  async remove(ctx: RequestTenantContext, actor: CrmActor, id: string) {
    const check = await this.deleteCheck(ctx, id);
    assertCanDelete(actor);
    if (!check.canDelete) throw new ConflictException(check.reason);
    try {
      await this.prisma.$transaction(async (tx) => {
        const contactIds = (await tx.contact.findMany({ where: this.tenant.scopeWhere(ctx, { accountId: id }), select: { id: true } })).map((c) => c.id);
        await tx.lead.updateMany({ where: this.tenant.scopeWhere(ctx, { convertedAccountId: id }), data: { convertedAccountId: null } });
        if (contactIds.length) {
          await tx.lead.updateMany({ where: this.tenant.scopeWhere(ctx, { convertedContactId: { in: contactIds } }), data: { convertedContactId: null } });
          await tx.contact.deleteMany({ where: this.tenant.scopeWhere(ctx, { id: { in: contactIds } }) });
        }
        await tx.customer.deleteMany({ where: this.tenant.scopeWhere(ctx, { id }) });
      });
    } catch (err) {
      rethrowRelationConflict(err, 'This customer is still linked to other records. Remove those links first.');
    }
    return { id };
  }

  // Returns all notes attached to the customer.
  async listNotes(ctx: RequestTenantContext, id: string) {
    await this.findOrThrow(ctx, id);
    return listEntityNotes(this.prisma, this.tenant, ctx, 'accountId', id);
  }

  // Creates and attaches a new note to the customer.
  async addNote(ctx: RequestTenantContext, id: string, dto: CreateNoteDto) {
    await this.findOrThrow(ctx, id);
    return createEntityNote(this.prisma, this.tenant, ctx, 'accountId', id, dto.body);
  }
}
