import { DealStage, Prisma } from '@prisma/client';
import { OPEN_DEAL_STAGES, STAGE_LABEL, STAGE_PROBABILITY } from './deal.constants';

const DAY_MS = 24 * 60 * 60 * 1000;

/** Allocates the next sequential tenant deal number (e.g. DEAL-1041). */
export function isClosedStage(stage: DealStage): boolean {
  return stage === DealStage.CLOSED_WON || stage === DealStage.CLOSED_LOST;
}

export function computeDaysInStage(stageChangedAt: Date): number {
  return Math.max(0, Math.floor((Date.now() - stageChangedAt.getTime()) / DAY_MS));
}

export function computeWeightedAmount(amount: number, stage: DealStage): number {
  return Math.round((amount * STAGE_PROBABILITY[stage]) / 100);
}

export interface DealStats {
  openPipeline: number;
  weightedForecast: number;
  wonValue: number;
  averageDealSize: number;
  openCount: number;
  totalDeals: number;
}

export function computeDealStats(rows: Array<{ amount: Prisma.Decimal | number; stage: DealStage }>): DealStats {
  let openPipeline = 0;
  let weightedForecast = 0;
  let wonValue = 0;
  let totalAmount = 0;
  let openCount = 0;

  for (const row of rows) {
    const amt = Number(row.amount);
    totalAmount += amt;
    if (OPEN_DEAL_STAGES.includes(row.stage)) {
      openCount += 1;
      openPipeline += amt;
      weightedForecast += (amt * STAGE_PROBABILITY[row.stage]) / 100;
    } else if (row.stage === DealStage.CLOSED_WON) {
      wonValue += amt;
    }
  }

  return {
    openPipeline,
    weightedForecast: Math.round(weightedForecast),
    wonValue,
    averageDealSize: rows.length > 0 ? Math.round(totalAmount / rows.length) : 0,
    openCount,
    totalDeals: rows.length,
  };
}

export function buildStageTransitionNote(fromStage: DealStage | null, toStage: DealStage, lossReason?: string | null, competitor?: string | null): string | null {
  if (toStage === DealStage.CLOSED_LOST && lossReason) {
    return competitor ? `Reason: ${lossReason} (competitor: ${competitor})` : `Reason: ${lossReason}`;
  }
  if (!fromStage) {
    return `Created in ${STAGE_LABEL[toStage]}`;
  }
  return null;
}
