import { Injectable, NotFoundException } from '@nestjs/common';
import { 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 type { ContactView } from './contact.constants';
import { CreateContactDto } from './dto/create-contact.dto';
import { UpdateContactDto } from './dto/update-contact.dto';
import { ListContactsQuery } from './dto/list-contacts.query';

const NOT_FOUND = 'Contact not found';

const contactSelect = {
  id: true,
  name: true,
  email: true,
  phone: true,
  title: true,
  lifecycle: true,
  lastActivityAt: true,
  accountId: true,
  createdAt: true,
  updatedAt: true,
  account: { select: { id: true, name: true, city: true, industry: true } },
  owner: { select: { id: true, name: true } },
} satisfies Prisma.ContactSelect;

export type ContactDto = Prisma.ContactGetPayload<{
  select: typeof contactSelect;
}>;
export type ContactCounts = Record<ContactView, number>;

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

  // Builds tenant-scoped query filter for contact tab views.
  private viewWhere(view: ContactView, userId: string): Prisma.ContactWhereInput {
    switch (view) {
      case 'mine':
        return { ownerId: userId };
      case 'cust':
        return { lifecycle: 'Customer' };
      case 'prosp':
        return { lifecycle: 'Prospect' };
      default:
        return {};
    }
  }

  // Verifies that a referenced account belongs to the tenant.
  private async assertAccountInTenant(ctx: RequestTenantContext, accountId: string | null | undefined): Promise<void> {
    if (!accountId) return;
    const account = await this.prisma.customer.findFirst({
      where: this.tenant.scopeWhere(ctx, { id: accountId }),
      select: { id: true },
    });
    if (!account) throw new NotFoundException('Account not found');
  }

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

  // Returns contact counts for all preset views within tenant scope.
  async counts(ctx: RequestTenantContext): Promise<ContactCounts> {
    const views: ContactView[] = ['all', 'mine', 'cust', 'prosp'];
    const values = await Promise.all(
      views.map((v) =>
        this.prisma.contact.count({
          where: this.tenant.scopeWhere(ctx, this.viewWhere(v, ctx.userId)),
        }),
      ),
    );
    return Object.fromEntries(views.map((v, i) => [v, values[i]])) as ContactCounts;
  }

  // Checks for existing contacts with matching email within tenant.
  async checkDuplicate(ctx: RequestTenantContext, email?: string, excludeId?: string) {
    const cleanEmail = email?.trim().toLowerCase();
    if (!cleanEmail) return [];
    return this.prisma.contact.findMany({
      where: this.tenant.scopeWhere(ctx, {
        ...(excludeId ? { id: { not: excludeId } } : {}),
        email: cleanEmail,
      }),
      take: 5,
      select: {
        id: true,
        name: true,
        email: true,
        account: { select: { id: true, name: true } },
      },
    });
  }

  // Returns paginated contacts matching filters, search queries, and sorting.
  async list(ctx: RequestTenantContext, q: ListContactsQuery) {
    const where = this.tenant.scopeWhere(ctx, {
      AND: [
        this.viewWhere(q.view, ctx.userId),
        q.lifecycle ? { lifecycle: q.lifecycle } : {},
        q.accountId ? { accountId: q.accountId } : {},
        q.ownerId ? { ownerId: q.ownerId } : {},
        q.createdFrom || q.createdTo
          ? {
              createdAt: {
                ...(q.createdFrom ? { gte: new Date(q.createdFrom) } : {}),
                ...(q.createdTo ? { lte: new Date(q.createdTo) } : {}),
              },
            }
          : {},
        q.q
          ? {
              OR: [{ name: { contains: q.q } }, { email: { contains: q.q } }, { title: { contains: q.q } }, { account: { name: { contains: q.q } } }],
            }
          : {},
      ],
    } satisfies Prisma.ContactWhereInput);

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

    const [total, rows, counts, accountsCount] = await Promise.all([
      this.prisma.contact.count({ where }),
      this.prisma.contact.findMany({
        where,
        orderBy,
        skip: (q.page - 1) * q.pageSize,
        take: q.pageSize,
        select: contactSelect,
      }),
      this.counts(ctx),
      this.prisma.customer.count({ where: this.tenant.scopeWhere(ctx) }),
    ]);

    return {
      items: rows,
      total,
      page: q.page,
      pageSize: q.pageSize,
      counts,
      accountsCount,
    };
  }

  // Retrieves single contact details including associated account deals.
  async get(ctx: RequestTenantContext, id: string) {
    const row = await this.prisma.contact.findFirst({
      where: this.tenant.scopeWhere(ctx, { id }),
      select: contactSelect,
    });
    if (!row) throw new NotFoundException(NOT_FOUND);

    const deals = row.accountId
      ? await this.prisma.deal.findMany({
          where: this.tenant.scopeWhere(ctx, { accountId: row.accountId }),
          orderBy: [{ createdAt: 'desc' }],
          select: {
            id: true,
            dealNumber: true,
            title: true,
            stage: true,
            amount: true,
          },
        })
      : [];

    return {
      ...row,
      deals: deals.map((d) => ({ ...d, amount: Number(d.amount) })),
    };
  }

  // Creates a new contact record within the tenant.
  async create(ctx: RequestTenantContext, dto: CreateContactDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const ownerId = dto.ownerId === undefined ? ctx.userId : dto.ownerId;
    await Promise.all([assertTenantOwner(this.prisma, tenantId, ownerId), this.assertAccountInTenant(ctx, dto.accountId)]);
    return this.prisma.contact.create({
      data: this.tenant.scopeCreate(ctx, {
        ...dto,
        email: dto.email || '',
        ownerId,
        lifecycle: dto.lifecycle ?? 'Prospect',
        lastActivityAt: new Date(),
      }),
      select: contactSelect,
    });
  }

  // Updates an existing contact record within the tenant.
  async update(ctx: RequestTenantContext, id: string, dto: UpdateContactDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    await this.findOrThrow(ctx, id);
    await Promise.all([assertTenantOwner(this.prisma, tenantId, dto.ownerId), this.assertAccountInTenant(ctx, dto.accountId)]);
    await this.prisma.contact.updateMany({
      where: this.tenant.scopeWhere(ctx, { id }),
      data: dto,
    });
    return this.get(ctx, id);
  }

  // Deletes a contact if the actor has permission and no conflicting relations.
  async remove(ctx: RequestTenantContext, actor: CrmActor, id: string) {
    await this.findOrThrow(ctx, id);
    assertCanDelete(actor);
    try {
      await this.prisma.contact.deleteMany({
        where: this.tenant.scopeWhere(ctx, { id }),
      });
    } catch (err) {
      rethrowRelationConflict(err, 'Cannot delete this contact because it has linked deals, tasks, or converted leads.');
    }
    return { id };
  }

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

  // Creates and attaches a new note to the contact, updating last activity.
  async addNote(ctx: RequestTenantContext, id: string, dto: CreateNoteDto) {
    await this.findOrThrow(ctx, id);
    return this.prisma.$transaction(async (tx) => {
      const note = await createEntityNote(tx, this.tenant, ctx, 'contactId', id, dto.body);
      await tx.contact.updateMany({
        where: this.tenant.scopeWhere(ctx, { id }),
        data: { lastActivityAt: new Date() },
      });
      return note;
    });
  }
}
