import { BadRequestException, 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 { DEAL_TAB_VIEWS, OPEN_DEAL_STAGES, STAGE_PROBABILITY, type DealTabView, type DealView } from './deal.constants';
import { computeDaysInStage, computeDealStats, computeWeightedAmount, isClosedStage, type DealStats } from './deal.helper';
import { NumberingService } from '../numbering/numbering.service';
import { CreateDealDto } from './dto/create-deal.dto';
import { ListDealsQuery } from './dto/list-deals.query';
import { MoveStageDto } from './dto/move-stage.dto';
import { UpdateDealDto } from './dto/update-deal.dto';

const NOT_FOUND = 'Deal not found';
const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;

export const dealSelect = {
  id: true,
  dealNumber: true,
  title: true,
  amount: true,
  stage: true,
  closeDate: true,
  engagementModel: true,
  estimatedHours: true,
  stageChangedAt: true,
  closedAt: true,
  lossReason: true,
  competitor: true,
  lostNotes: true,
  accountId: true,
  contactId: true,
  ownerId: true,
  createdAt: true,
  updatedAt: true,
  account: { select: { id: true, name: true } },
  contact: { select: { id: true, name: true, email: true } },
  owner: { select: { id: true, name: true } },
} satisfies Prisma.DealSelect;

type DealRow = Prisma.DealGetPayload<{ select: typeof dealSelect }>;

export type DealDto = Omit<DealRow, 'amount'> & {
  amount: number;
  probability: number;
  weightedAmount: number;
  daysInStage: number;
};

export type DealCounts = Record<DealTabView, number>;

export type DealFilters = Partial<Pick<ListDealsQuery, 'view' | 'stage' | 'ownerId' | 'createdFrom' | 'createdTo' | 'closeDateFrom' | 'closeDateTo' | 'q'>>;

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

  // Maps database deal record to DealDto with calculated metrics.
  private toDto(row: DealRow): DealDto {
    const amount = Number(row.amount);
    return {
      ...row,
      amount,
      probability: STAGE_PROBABILITY[row.stage],
      weightedAmount: computeWeightedAmount(amount, row.stage),
      daysInStage: computeDaysInStage(row.stageChangedAt),
    };
  }

  // Builds tenant-scoped query filter for deal tab views.
  private viewWhere(view: DealView, userId: string): Prisma.DealWhereInput {
    const open = { stage: { in: [...OPEN_DEAL_STAGES] } };
    switch (view) {
      case 'board':
        return {};
      case 'mine':
        return { ...open, ownerId: userId };
      case 'closing': {
        const startOfToday = new Date();
        startOfToday.setHours(0, 0, 0, 0);
        const in30Days = new Date(startOfToday.getTime() + THIRTY_DAYS_MS);
        return { ...open, closeDate: { gte: startOfToday, lte: in30Days } };
      }
      case 'won':
        return { stage: DealStage.CLOSED_WON };
      case 'lost':
        return { stage: DealStage.CLOSED_LOST };
      default:
        return open;
    }
  }

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

  // Verifies that a referenced account belongs to the tenant.
  private async assertTenantAccount(ctx: RequestTenantContext, accountId: string) {
    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');
  }

  // Verifies that a referenced contact belongs to the tenant and to the deal's customer.
  private async assertTenantContact(ctx: RequestTenantContext, contactId: string | null | undefined, accountId: string | null | undefined) {
    if (!contactId) return;
    const contact = await this.prisma.contact.findFirst({
      where: this.tenant.scopeWhere(ctx, { id: contactId }),
      select: { id: true, accountId: true },
    });
    if (!contact) throw new NotFoundException('Contact not found');
    if (contact.accountId && accountId && contact.accountId !== accountId) {
      throw new BadRequestException('Choose a contact from this customer');
    }
  }

  // Requires a loss reason whenever a deal is marked Closed Lost.
  private assertLossReason(stage: DealStage | undefined, lossReason: string | null | undefined) {
    if (stage === DealStage.CLOSED_LOST && !lossReason?.trim()) {
      throw new BadRequestException('Select a loss reason');
    }
  }

  // Computes aggregate deal statistics and counts for all deal views.
  async summary(ctx: RequestTenantContext): Promise<{ counts: DealCounts; stats: DealStats }> {
    const [tabValues, allRows] = await Promise.all([
      Promise.all(
        DEAL_TAB_VIEWS.map((v) =>
          this.prisma.deal.count({
            where: this.tenant.scopeWhere(ctx, this.viewWhere(v, ctx.userId)),
          }),
        ),
      ),
      this.prisma.deal.findMany({
        where: this.tenant.scopeWhere(ctx, {}),
        select: { amount: true, stage: true },
      }),
    ]);

    const counts = Object.fromEntries(DEAL_TAB_VIEWS.map((v, i) => [v, tabValues[i]])) as DealCounts;

    return {
      counts,
      stats: computeDealStats(allRows),
    };
  }

  /** Builds the tenant-scoped deal filter shared by the list and the export. */
  filterWhere(ctx: RequestTenantContext, q: DealFilters): Prisma.DealWhereInput {
    return this.tenant.scopeWhere(ctx, {
      AND: [
        this.viewWhere(q.view ?? 'all', ctx.userId),
        q.stage ? { stage: q.stage } : {},
        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.closeDateFrom || q.closeDateTo
          ? {
              closeDate: {
                ...(q.closeDateFrom ? { gte: new Date(q.closeDateFrom) } : {}),
                ...(q.closeDateTo ? { lte: new Date(q.closeDateTo) } : {}),
              },
            }
          : {},
        q.q
          ? {
              OR: [{ title: { contains: q.q } }, { dealNumber: { contains: q.q } }, { account: { name: { contains: q.q } } }],
            }
          : {},
      ],
    } satisfies Prisma.DealWhereInput);
  }

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

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

    const [total, rows, sum] = await Promise.all([
      this.prisma.deal.count({ where }),
      this.prisma.deal.findMany({
        where,
        orderBy,
        skip: (q.page - 1) * q.pageSize,
        take: q.pageSize,
        select: dealSelect,
      }),
      this.summary(ctx),
    ]);

    return {
      items: rows.map((r) => this.toDto(r)),
      total,
      page: q.page,
      pageSize: q.pageSize,
      counts: sum.counts,
      stats: sum.stats,
    };
  }

  // Retrieves single deal details including stage history and converted leads.
  async get(ctx: RequestTenantContext, id: string) {
    const row = await this.prisma.deal.findFirst({
      where: this.tenant.scopeWhere(ctx, { id }),
      select: {
        ...dealSelect,
        stageHistory: {
          orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
          select: {
            id: true,
            fromStage: true,
            toStage: true,
            note: true,
            createdAt: true,
            changedBy: { select: { id: true, name: true } },
          },
        },
        convertedLeads: {
          select: { id: true, name: true },
        },
      },
    });
    if (!row) throw new NotFoundException(NOT_FOUND);
    const { stageHistory, convertedLeads, ...base } = row;
    return {
      ...this.toDto(base),
      stageHistory,
      convertedLeads,
    };
  }

  // Creates a deal and initial stage history inside an existing transaction.
  async createInTransaction(
    tx: Prisma.TransactionClient,
    ctx: RequestTenantContext,
    input: {
      title: string;
      accountId: string;
      contactId?: string | null;
      amount: number;
      stage?: DealStage;
      closeDate?: Date | null;
      engagementModel?: string | null;
      estimatedHours?: number | null;
      ownerId?: string | null;
      lossReason?: string | null;
      competitor?: string | null;
      lostNotes?: string | null;
    },
  ): Promise<DealDto> {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const dealNumber = await this.numbering.getNextNumber(tenantId, 'DEAL', 'GLOBAL', tx);
    const stage = input.stage ?? DealStage.QUALIFICATION;
    const now = new Date();
    const isLost = stage === DealStage.CLOSED_LOST;

    const row = await tx.deal.create({
      data: this.tenant.scopeCreate(ctx, {
        dealNumber,
        title: input.title,
        accountId: input.accountId,
        contactId: input.contactId ?? null,
        amount: input.amount,
        stage,
        closeDate: input.closeDate ?? null,
        engagementModel: input.engagementModel ?? null,
        estimatedHours: input.estimatedHours ?? null,
        ownerId: input.ownerId ?? null,
        stageChangedAt: now,
        closedAt: isClosedStage(stage) ? now : null,
        lossReason: isLost ? (input.lossReason ?? null) : null,
        competitor: isLost ? (input.competitor ?? null) : null,
        lostNotes: isLost ? (input.lostNotes ?? null) : null,
      }),
      select: dealSelect,
    });

    await tx.dealStageHistory.create({
      data: {
        tenantId,
        dealId: row.id,
        fromStage: null,
        toStage: stage,
        changedById: ctx.userId ?? null,
        note: 'Deal created',
      },
    });

    return this.toDto(row);
  }

  // Creates a new deal and records initial stage history.
  async create(ctx: RequestTenantContext, dto: CreateDealDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const ownerId = dto.ownerId === undefined ? ctx.userId : dto.ownerId;
    this.assertLossReason(dto.stage, dto.lossReason);
    await Promise.all([this.assertTenantAccount(ctx, dto.accountId), this.assertTenantContact(ctx, dto.contactId, dto.accountId), assertTenantOwner(this.prisma, tenantId, ownerId)]);

    return this.prisma.$transaction((tx) =>
      this.createInTransaction(tx, ctx, {
        title: dto.title,
        accountId: dto.accountId,
        contactId: dto.contactId,
        amount: dto.amount,
        stage: dto.stage,
        closeDate: dto.closeDate ? new Date(dto.closeDate) : null,
        engagementModel: dto.engagementModel,
        estimatedHours: dto.estimatedHours,
        ownerId,
        lossReason: dto.lossReason,
        competitor: dto.competitor,
        lostNotes: dto.lostNotes,
      }),
    );
  }

  // Updates an existing deal and logs stage transition history when stage changes.
  async update(ctx: RequestTenantContext, id: string, dto: UpdateDealDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    const existing = await this.findOrThrow(ctx, id);

    const nextStage = dto.stage ?? existing.stage;
    const stageChanged = dto.stage !== undefined && dto.stage !== existing.stage;
    if (stageChanged) this.assertLossReason(nextStage, dto.lossReason);
    const targetAccountId = dto.accountId ?? existing.accountId;
    const accountChanged = dto.accountId !== undefined && dto.accountId !== existing.accountId;
    await Promise.all([dto.accountId ? this.assertTenantAccount(ctx, dto.accountId) : Promise.resolve(), this.assertTenantContact(ctx, dto.contactId, targetAccountId), assertTenantOwner(this.prisma, tenantId, dto.ownerId)]);
    const dropStaleContact = accountChanged && dto.contactId === undefined && existing.contactId !== null;
    const isLost = nextStage === DealStage.CLOSED_LOST;
    const now = new Date();

    const data: Prisma.DealUncheckedUpdateManyInput = {
      ...(dto.title !== undefined ? { title: dto.title } : {}),
      ...(dto.accountId !== undefined ? { accountId: dto.accountId } : {}),
      ...(dto.contactId !== undefined ? { contactId: dto.contactId } : dropStaleContact ? { contactId: null } : {}),
      ...(dto.amount !== undefined ? { amount: dto.amount } : {}),
      ...(dto.closeDate !== undefined ? { closeDate: dto.closeDate ? new Date(dto.closeDate) : null } : {}),
      ...(dto.engagementModel !== undefined ? { engagementModel: dto.engagementModel } : {}),
      ...(dto.estimatedHours !== undefined ? { estimatedHours: dto.estimatedHours } : {}),
      ...(dto.ownerId !== undefined ? { ownerId: dto.ownerId } : {}),
      ...(stageChanged
        ? {
            stage: nextStage,
            stageChangedAt: now,
            closedAt: isClosedStage(nextStage) ? now : null,
          }
        : {}),
      ...(isLost
        ? {
            ...(dto.lossReason !== undefined ? { lossReason: dto.lossReason } : {}),
            ...(dto.competitor !== undefined ? { competitor: dto.competitor } : {}),
            ...(dto.lostNotes !== undefined ? { lostNotes: dto.lostNotes } : {}),
          }
        : stageChanged
          ? { lossReason: null, competitor: null, lostNotes: null }
          : {}),
    };

    await this.prisma.$transaction(async (tx) => {
      await tx.deal.updateMany({
        where: this.tenant.scopeWhere(ctx, { id }),
        data,
      });

      if (stageChanged) {
        await tx.dealStageHistory.create({
          data: {
            tenantId,
            dealId: id,
            fromStage: existing.stage,
            toStage: nextStage,
            changedById: ctx.userId ?? null,
            note: dto.lossReason ? `Reason: ${dto.lossReason}` : null,
          },
        });
      }
    });

    return this.get(ctx, id);
  }

  // Transitions deal stage and records stage history note.
  async moveStage(ctx: RequestTenantContext, id: string, dto: MoveStageDto) {
    const existing = await this.findOrThrow(ctx, id);
    const stageChanged = dto.stage !== existing.stage;
    if (stageChanged) this.assertLossReason(dto.stage, dto.lossReason);
    const isLost = dto.stage === DealStage.CLOSED_LOST;
    const now = new Date();

    await this.prisma.$transaction(async (tx) => {
      await tx.deal.updateMany({
        where: this.tenant.scopeWhere(ctx, { id }),
        data: {
          stage: dto.stage,
          ...(stageChanged
            ? {
                stageChangedAt: now,
                closedAt: isClosedStage(dto.stage) ? now : null,
              }
            : {}),
          ...(isLost
            ? {
                lossReason: dto.lossReason ?? null,
                competitor: dto.competitor ?? null,
                lostNotes: dto.lostNotes ?? null,
              }
            : { lossReason: null, competitor: null, lostNotes: null }),
        },
      });

      if (stageChanged) {
        await tx.dealStageHistory.create({
          data: {
            tenantId: this.tenant.getRequiredTenantId(ctx),
            dealId: id,
            fromStage: existing.stage,
            toStage: dto.stage,
            changedById: ctx.userId ?? null,
            note: dto.note ?? (dto.lossReason ? `Reason: ${dto.lossReason}` : null),
          },
        });
      }
    });

    return this.get(ctx, id);
  }

  // Deletes a deal, unlinking the lead it was converted from; projects, quotes or invoices still block it.
  async remove(ctx: RequestTenantContext, actor: CrmActor, id: string) {
    await this.findOrThrow(ctx, id);
    assertCanDelete(actor);
    const projects = await this.prisma.project.count({ where: this.tenant.scopeWhere(ctx, { dealId: id }) });
    if (projects > 0) {
      throw new ConflictException('This deal has a project. Delete or reassign the project first.');
    }
    try {
      await this.prisma.$transaction(async (tx) => {
        await tx.lead.updateMany({ where: this.tenant.scopeWhere(ctx, { convertedDealId: id }), data: { convertedDealId: null } });
        await tx.deal.deleteMany({ where: this.tenant.scopeWhere(ctx, { id }) });
      });
    } catch (err) {
      rethrowRelationConflict(err, 'This deal has a project, quote or invoice. Delete those first.');
    }
    return { id };
  }

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

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