import 'dotenv/config';
import {
  AcquisitionChannel,
  ActivityType,
  AuditAction,
  ClientSector,
  CompanySize,
  Department,
  LeadStatus,
  OpportunityStage,
  Prisma,
  PrismaClient,
  ProjectStatus,
  QuoteStatus,
  RenewalStatus,
  ServicePole,
  TicketPriority,
  TicketStatus,
  UserRole,
} from '@prisma/client';
import * as argon2 from 'argon2';

const prisma = new PrismaClient();

// =============================================================================
// UTILITAIRES DÉTERMINISTES & HELPERS MÉTIER
// =============================================================================

function createRng(seed: number): () => number {
  let state = seed >>> 0;
  return (): number => {
    state = (state + 0x6d2b79f5) | 0;
    let t = Math.imul(state ^ (state >>> 15), 1 | state);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

const rng = createRng(20260401);

function pick<T>(items: readonly T[], index: number): T {
  if (items.length === 0) {
    throw new Error('Cannot pick from an empty array');
  }
  const safeIndex = ((index % items.length) + items.length) % items.length;
  const item = items[safeIndex];
  if (item === undefined) {
    throw new Error('Unexpected undefined element in pick');
  }
  return item;
}

function addDays(base: Date, days: number): Date {
  const result = new Date(base.getTime());
  result.setUTCDate(result.getUTCDate() + days);
  return result;
}

function padRef(prefix: string, seq: number, year = 2026): string {
  return `${prefix}-${year}-${String(seq).padStart(4, '0')}`;
}

const SECTOR_LABELS_FR: Record<ClientSector, string> = {
  [ClientSector.COMMERCE_ECOMMERCE]: 'Commerce & E-commerce',
  [ClientSector.SERVICES_ENTREPRISES]: 'Services aux entreprises',
  [ClientSector.TOURISME_LOISIRS]: 'Tourisme & Loisirs',
  [ClientSector.INDUSTRIE]: 'Industrie',
};

const POLE_LABELS_FR: Record<ServicePole, string> = {
  [ServicePole.MARKETING_DIGITAL]: 'Marketing Digital',
  [ServicePole.DEV_WEB_UX]: 'Développement Web & UX/UI',
  [ServicePole.MAINTENANCE_HEBERGEMENT]: 'Maintenance & Hébergement',
};

function computeLeadScore(params: {
  leadStatus: LeadStatus;
  seedIndex: number;
  isDecisionMaker: boolean;
  size: CompanySize;
  hasPhone: boolean;
}): number {
  const signalBonus =
    (params.isDecisionMaker ? 8 : 0) +
    (params.size === CompanySize.GE ? 6 : params.size === CompanySize.ETI ? 4 : 0) +
    (params.hasPhone ? 4 : 0);
  const jitter = (params.seedIndex * 7) % 13;

  switch (params.leadStatus) {
    case LeadStatus.DISQUALIFIED:
      return Math.min(38, 20 + ((params.seedIndex * 5 + signalBonus) % 19));
    case LeadStatus.NEW:
      return Math.min(75, 45 + ((signalBonus + jitter) % 31));
    case LeadStatus.QUALIFYING:
      return Math.min(78, 55 + ((signalBonus + jitter) % 24));
    case LeadStatus.QUALIFIED:
      return Math.min(95, 75 + ((signalBonus + jitter) % 21));
  }
}

/**
 * Répartit un montant total exact (ex: 648 000 €) sur N missions tout en conservant
 * des montants fixes pour d'éventuelles missions internationales (36 000 €).
 */
function buildExactAmounts(count: number, totalEur: number, fixedPositions: readonly number[]): number[] {
  const base = Math.round(totalEur / count);
  const amounts = new Array<number>(count).fill(base);

  const fixedSet = new Set<number>(fixedPositions);
  const adjustableIndices: number[] = [];
  for (let i = 0; i < count; i += 1) {
    if (!fixedSet.has(i)) {
      adjustableIndices.push(i);
    }
  }

  const deltas = [-8000, 8000, -5500, 5500, -3500, 3500, -6000, 6000, -2500, 2500];
  for (let i = 0; i + 1 < adjustableIndices.length; i += 2) {
    const idxA = adjustableIndices[i];
    const idxB = adjustableIndices[i + 1];
    if (idxA !== undefined && idxB !== undefined) {
      const delta = pick(deltas, i);
      amounts[idxA] = (amounts[idxA] ?? base) + delta;
      amounts[idxB] = (amounts[idxB] ?? base) - delta;
    }
  }

  const currentSum = amounts.reduce((acc, v) => acc + v, 0);
  const diff = totalEur - currentSum;
  if (diff !== 0) {
    const lastIdx = adjustableIndices[adjustableIndices.length - 1] ?? 0;
    amounts[lastIdx] = (amounts[lastIdx] ?? base) + diff;
  }

  return amounts;
}

// =============================================================================
// DONNÉES NOMINATIVES RÉALISTES BLOOM
// =============================================================================

interface SeedUserSpec {
  email: string;
  firstName: string;
  lastName: string;
  jobTitle: string;
  role: UserRole;
  department: Department;
  isActive: boolean;
}

const USERS_SPEC: readonly SeedUserSpec[] = [
  // 1. Direction (4 ADMIN)
  {
    email: 'admin@bloom-agency.fr',
    firstName: 'Claire',
    lastName: 'Morel',
    jobTitle: 'Co-fondatrice & CEO',
    role: UserRole.ADMIN,
    department: Department.DIRECTION,
    isActive: true,
  },
  {
    email: 'julien.lefevre@bloom-agency.fr',
    firstName: 'Julien',
    lastName: 'Lefèvre',
    jobTitle: 'Co-fondateur & Directeur Général',
    role: UserRole.ADMIN,
    department: Department.DIRECTION,
    isActive: true,
  },
  {
    email: 'sophie.garcia@bloom-agency.fr',
    firstName: 'Sophie',
    lastName: 'Garcia',
    jobTitle: 'Directrice des Opérations',
    role: UserRole.ADMIN,
    department: Department.DIRECTION,
    isActive: true,
  },
  {
    email: 'marc.delacroix@bloom-agency.fr',
    firstName: 'Marc',
    lastName: 'Delacroix',
    jobTitle: 'Directeur Conseil & Stratégie',
    role: UserRole.ADMIN,
    department: Department.DIRECTION,
    isActive: true,
  },

  // 2. Équipe Commerciale (5 SALES)
  {
    email: 'commercial@bloom-agency.fr',
    firstName: 'Antoine',
    lastName: 'Rousseau',
    jobTitle: 'Commercial Senior & Account Executive',
    role: UserRole.SALES,
    department: Department.SALES,
    isActive: true,
  },
  {
    email: 'camille.bernard@bloom-agency.fr',
    firstName: 'Camille',
    lastName: 'Bernard',
    jobTitle: 'Account Executive Grands Comptes',
    role: UserRole.SALES,
    department: Department.SALES,
    isActive: true,
  },
  {
    email: 'lucas.petit@bloom-agency.fr',
    firstName: 'Lucas',
    lastName: 'Petit',
    jobTitle: 'Business Developer B2B',
    role: UserRole.SALES,
    department: Department.SALES,
    isActive: true,
  },
  {
    email: 'ines.laurent@bloom-agency.fr',
    firstName: 'Inès',
    lastName: 'Laurent',
    jobTitle: 'Account Manager Fidélisation',
    role: UserRole.SALES,
    department: Department.SALES,
    isActive: true,
  },
  {
    email: 'thomas.girard@bloom-agency.fr',
    firstName: 'Thomas',
    lastName: 'Girard',
    jobTitle: 'Business Developer Inbound',
    role: UserRole.SALES,
    department: Department.SALES,
    isActive: true,
  },

  // 3. Équipe Marketing (10 MARKETING : 8 Marketeurs + 2 Graphistes)
  {
    email: 'marketing@bloom-agency.fr',
    firstName: 'Élodie',
    lastName: 'Fontaine',
    jobTitle: 'Responsable Acquisition & Growth',
    role: UserRole.MARKETING,
    department: Department.MARKETING,
    isActive: true,
  },
  {
    email: 'hugo.mercier@bloom-agency.fr',
    firstName: 'Hugo',
    lastName: 'Mercier',
    jobTitle: 'Consultant SEO Senior',
    role: UserRole.MARKETING,
    department: Department.MARKETING,
    isActive: true,
  },
  {
    email: 'chloe.robin@bloom-agency.fr',
    firstName: 'Chloé',
    lastName: 'Robin',
    jobTitle: 'Traffic Manager Paid Media',
    role: UserRole.MARKETING,
    department: Department.MARKETING,
    isActive: true,
  },
  {
    email: 'mathieu.faure@bloom-agency.fr',
    firstName: 'Mathieu',
    lastName: 'Faure',
    jobTitle: 'Spécialiste CRM & Emailing',
    role: UserRole.MARKETING,
    department: Department.MARKETING,
    isActive: true,
  },
  {
    email: 'manon.chevalier@bloom-agency.fr',
    firstName: 'Manon',
    lastName: 'Chevalier',
    jobTitle: 'Content Strategist B2B',
    role: UserRole.MARKETING,
    department: Department.MARKETING,
    isActive: true,
  },
  {
    email: 'paul.blanc@bloom-agency.fr',
    firstName: 'Paul',
    lastName: 'Blanc',
    jobTitle: 'Consultant Social Ads',
    role: UserRole.MARKETING,
    department: Department.MARKETING,
    isActive: true,
  },
  {
    email: 'sarah.dubois@bloom-agency.fr',
    firstName: 'Sarah',
    lastName: 'Dubois',
    jobTitle: 'Consultante Web Analytics',
    role: UserRole.MARKETING,
    department: Department.MARKETING,
    isActive: true,
  },
  {
    email: 'nathan.vincent@bloom-agency.fr',
    firstName: 'Nathan',
    lastName: 'Vincent',
    jobTitle: 'Chargé d’Acquisition SDR',
    role: UserRole.MARKETING,
    department: Department.MARKETING,
    isActive: true,
  },
  {
    email: 'lea.muller@bloom-agency.fr',
    firstName: 'Léa',
    lastName: 'Muller',
    jobTitle: 'Graphiste Brand Designer',
    role: UserRole.MARKETING,
    department: Department.MARKETING,
    isActive: true,
  },
  {
    email: 'bastien.henry@bloom-agency.fr',
    firstName: 'Bastien',
    lastName: 'Henry',
    jobTitle: 'Motion & Graphic Designer',
    role: UserRole.MARKETING,
    department: Department.MARKETING,
    isActive: true,
  },

  // 4. Équipe Production / Delivery (16 DELIVERY : 3 PM + 8 Devs + 3 UX/UI + 2 Infra)
  {
    email: 'delivery@bloom-agency.fr',
    firstName: 'Romain',
    lastName: 'Vasseur',
    jobTitle: 'Chef de Projet Digital Senior',
    role: UserRole.DELIVERY,
    department: Department.PROJECT_MANAGEMENT,
    isActive: true,
  },
  {
    email: 'clara.legrand@bloom-agency.fr',
    firstName: 'Clara',
    lastName: 'Legrand',
    jobTitle: 'Cheffe de Projet Web & E-commerce',
    role: UserRole.DELIVERY,
    department: Department.PROJECT_MANAGEMENT,
    isActive: true,
  },
  {
    email: 'maxime.perrin@bloom-agency.fr',
    firstName: 'Maxime',
    lastName: 'Perrin',
    jobTitle: 'Chef de Projet Campagnes & Data',
    role: UserRole.DELIVERY,
    department: Department.PROJECT_MANAGEMENT,
    isActive: true,
  },
  {
    email: 'alexandre.morin@bloom-agency.fr',
    firstName: 'Alexandre',
    lastName: 'Morin',
    jobTitle: 'Lead Développeur Full-Stack',
    role: UserRole.DELIVERY,
    department: Department.DEV_WEB,
    isActive: true,
  },
  {
    email: 'julie.renard@bloom-agency.fr',
    firstName: 'Julie',
    lastName: 'Renard',
    jobTitle: 'Développeuse Front-End React',
    role: UserRole.DELIVERY,
    department: Department.DEV_WEB,
    isActive: true,
  },
  {
    email: 'kevin.marchand@bloom-agency.fr',
    firstName: 'Kévin',
    lastName: 'Marchand',
    jobTitle: 'Développeur Back-End Node.js',
    role: UserRole.DELIVERY,
    department: Department.DEV_WEB,
    isActive: true,
  },
  {
    email: 'nina.gauthier@bloom-agency.fr',
    firstName: 'Nina',
    lastName: 'Gauthier',
    jobTitle: 'Développeuse E-commerce Shopify/Magento',
    role: UserRole.DELIVERY,
    department: Department.DEV_WEB,
    isActive: true,
  },
  {
    email: 'quentin.duval@bloom-agency.fr',
    firstName: 'Quentin',
    lastName: 'Duval',
    jobTitle: 'Développeur Full-Stack TypeScript',
    role: UserRole.DELIVERY,
    department: Department.DEV_WEB,
    isActive: true,
  },
  {
    email: 'marine.lopez@bloom-agency.fr',
    firstName: 'Marine',
    lastName: 'Lopez',
    jobTitle: 'Développeuse WordPress & Headless',
    role: UserRole.DELIVERY,
    department: Department.DEV_WEB,
    isActive: true,
  },
  {
    email: 'florian.simon@bloom-agency.fr',
    firstName: 'Florian',
    lastName: 'Simon',
    jobTitle: 'Développeur Front-End Next.js',
    role: UserRole.DELIVERY,
    department: Department.DEV_WEB,
    isActive: true,
  },
  {
    email: 'oceane.brun@bloom-agency.fr',
    firstName: 'Océane',
    lastName: 'Brun',
    jobTitle: 'Développeuse QA & Intégration',
    role: UserRole.DELIVERY,
    department: Department.DEV_WEB,
    isActive: true,
  },
  {
    email: 'eva.picard@bloom-agency.fr',
    firstName: 'Éva',
    lastName: 'Picard',
    jobTitle: 'Lead UX/UI Designer',
    role: UserRole.DELIVERY,
    department: Department.UX_UI,
    isActive: true,
  },
  {
    email: 'theo.colin@bloom-agency.fr',
    firstName: 'Théo',
    lastName: 'Colin',
    jobTitle: 'UX Researcher & Product Designer',
    role: UserRole.DELIVERY,
    department: Department.UX_UI,
    isActive: true,
  },
  {
    email: 'louise.barbier@bloom-agency.fr',
    firstName: 'Louise',
    lastName: 'Barbier',
    jobTitle: 'UI Designer Design System',
    role: UserRole.DELIVERY,
    department: Department.UX_UI,
    isActive: true,
  },
  {
    email: 'damien.arnaud@bloom-agency.fr',
    firstName: 'Damien',
    lastName: 'Arnaud',
    jobTitle: 'Ingénieur DevOps & Hébergement Cloud',
    role: UserRole.DELIVERY,
    department: Department.INFRASTRUCTURE,
    isActive: true,
  },
  {
    email: 'valentin.roche@bloom-agency.fr',
    firstName: 'Valentin',
    lastName: 'Roche',
    jobTitle: 'Administrateur Systèmes & TMA',
    role: UserRole.DELIVERY,
    department: Department.INFRASTRUCTURE,
    isActive: true,
  },

  // 5. Support interne (3 : 1 RH + 2 Product Managers hors accès opérationnel CRM)
  {
    email: 'rh@bloom-agency.fr',
    firstName: 'Hélène',
    lastName: 'Caron',
    jobTitle: 'Responsable Ressources Humaines',
    role: UserRole.ADMIN,
    department: Department.HR,
    isActive: false,
  },
  {
    email: 'pm.interne1@bloom-agency.fr',
    firstName: 'Adrien',
    lastName: 'Masson',
    jobTitle: 'Product Manager Interne',
    role: UserRole.ADMIN,
    department: Department.DIRECTION,
    isActive: false,
  },
  {
    email: 'pm.interne2@bloom-agency.fr',
    firstName: 'Céline',
    lastName: 'Guillot',
    jobTitle: 'Product Manager R&D',
    role: UserRole.ADMIN,
    department: Department.DIRECTION,
    isActive: false,
  },
];

interface SectorSpec {
  sector: ClientSector;
  totalCompanies: number;
  activeClients: number;
  sizes: readonly { size: CompanySize; count: number }[];
  cities: readonly string[];
  companyNames: readonly string[];
}

const SECTORS_SPEC: readonly SectorSpec[] = [
  {
    sector: ClientSector.COMMERCE_ECOMMERCE,
    totalCompanies: 32,
    activeClients: 22,
    sizes: [
      { size: CompanySize.PME, count: 22 },
      { size: CompanySize.ETI, count: 8 },
      { size: CompanySize.GE, count: 2 },
    ],
    cities: ['Paris', 'Lyon', 'Bordeaux', 'Lille', 'Nantes', 'Saint-Cloud'],
    companyNames: [
      'Maison Valmont Paris', 'Optique Lumière', 'Atelier Botanique', 'Nordic Home Store',
      'Cycles & Mobilité', 'Terroir Gourmand', 'Vêtements Mérinos', 'Cosmétiques Éclat',
      'Librairie Horizon', 'Bazar Design', 'Café des Alpes', 'Sport & Montagne',
      'Jardin Urbain', 'Cave Prestige', 'Mobilier Scandi', 'Mode Éthique France',
      'Bijouterie Solène', 'Boulangerie Artisanale Pro', 'Jouets en Bois', 'TechAccessoires',
      'Bruxelles Gourmet Select', 'Geneva Luxury Retail',
      'Épicerie Fine Lyon', 'Chaussures Vendôme', 'Pâtisserie Clément', 'Papeterie Moderne',
      'Animalerie Bonheur', 'Maison du Lin', 'Luminaires Studio', 'Parfums de Grasse',
      'Équipement Running', 'Vinyle & Son',
    ],
  },
  {
    sector: ClientSector.SERVICES_ENTREPRISES,
    totalCompanies: 24,
    activeClients: 17,
    sizes: [
      { size: CompanySize.PME, count: 17 },
      { size: CompanySize.ETI, count: 6 },
      { size: CompanySize.GE, count: 1 },
    ],
    cities: ['Paris', 'La Défense', 'Neuilly-sur-Seine', 'Toulouse', 'Marseille', 'Strasbourg'],
    companyNames: [
      'Cabinet Audencia Conseil', 'Nexis Legal Partners', 'FormaPro Academy', 'AssurPrev Entreprises',
      'TalentBridge RH', 'DataFlow Analytics', 'GreenFacility Services', 'Finexa Expertise',
      'LogiSmart Supply', 'SecurIT Cloud', 'Archipel Architecture', 'BatiNormes Contrôle',
      'Pulse Communication', 'Eventis Corporate', 'FleetManage France', 'Solvencia Recouvrement',
      'LuxTrust Advisory',
      'ClimatConseil B2B', 'MediStaff Intérim', 'LegalTech Solutions', 'ProClean Tertiaire',
      'OptiFlux Achats', 'Synergie Formation', 'Veritas Audit',
    ],
  },
  {
    sector: ClientSector.TOURISME_LOISIRS,
    totalCompanies: 16,
    activeClients: 11,
    sizes: [
      { size: CompanySize.PME, count: 11 },
      { size: CompanySize.ETI, count: 4 },
      { size: CompanySize.GE, count: 1 },
    ],
    cities: ['Nice', 'Annecy', 'Biarritz', 'Chamonix', 'Aix-en-Provence', 'Saint-Malo'],
    companyNames: [
      'Hôtels Riviera Collection', 'Alpinia Resorts', 'Croisières Atlantique', 'Domaine des Vignes',
      'Évasion Thermale', 'Parc Aventure Sologne', 'Camping Les Pins', 'Voyages Horizon Bleu',
      'Spa Mont-Blanc', 'Golf & Château Loire', 'London Heritage Tours',
      'Nautic Club Méditerranée', 'Gîtes de Charme', 'Musée Interactif Val', 'SkiPass Services',
      'Loisirs Outdoor Jura',
    ],
  },
  {
    sector: ClientSector.INDUSTRIE,
    totalCompanies: 8,
    activeClients: 5,
    sizes: [
      { size: CompanySize.PME, count: 6 },
      { size: CompanySize.ETI, count: 2 },
      { size: CompanySize.GE, count: 0 },
    ],
    cities: ['Grenoble', 'Clermont-Ferrand', 'Saint-Étienne', 'Mulhouse', 'Rennes'],
    companyNames: [
      'MécaPrécision Rhône', 'Plasturgie Durable', 'AeroParts Composites', 'Énergie Solaire Indus',
      'Automatisme Loire',
      'Métallurgie Moderne', 'Emballages ÉcoPack', 'Outillage ProTech',
    ],
  },
];

const FIRST_NAMES = [
  'Julien', 'Sophie', 'Nicolas', 'Aurélie', 'Benoît', 'Céline', 'Matthieu', 'Claire',
  'Sébastien', 'Caroline', 'Pierre', 'Virginie', 'Guillaume', 'Audrey', 'Olivier', 'Emilie',
  'Vincent', 'Laetitia', 'Romain', 'Delphine', 'Arnaud', 'Stéphanie', 'Christophe', 'Mathilde',
] as const;

const LAST_NAMES = [
  'Martin', 'Bernard', 'Thomas', 'Petit', 'Robert', 'Richard', 'Durand', 'Dubois',
  'Moreau', 'Laurent', 'Simon', 'Michel', 'Lefebvre', 'Leroy', 'Roux', 'David',
  'Bertrand', 'Morel', 'Fournier', 'Girard', 'Bonnet', 'Dupont', 'Lambert', 'Fontaine',
] as const;

const DECISION_TITLES = [
  'Directeur Marketing', 'CEO / Dirigeant', 'Directrice E-commerce', 'Directeur Digital', 'VP Sales & Growth',
] as const;

const NON_DECISION_TITLES = [
  'Chargé de Communication', 'Chef de Projet Digital', 'Responsable CRM', 'Traffic Manager', 'Assistante Marketing',
] as const;

// =============================================================================
// SCRIPT PRINCIPAL DE SEED
// =============================================================================

async function main(): Promise<void> {
  if (process.env.NODE_ENV === 'production' && process.env.SEED_FORCE !== 'true') {
    throw new Error('Seed bloqué en environnement production (définir SEED_FORCE=true pour forcer).');
  }

  const now = new Date();
  console.log('🌱 Démarrage du seed Bloom CRM...');

  // 1. Nettoyage idempotent dans l'ordre inverse des relations
  await prisma.$transaction([
    prisma.auditLog.deleteMany(),
    prisma.notification.deleteMany(),
    prisma.document.deleteMany(),
    prisma.activity.deleteMany(),
    prisma.supportTicket.deleteMany(),
    prisma.contract.deleteMany(),
    prisma.project.deleteMany(),
    prisma.quote.deleteMany(),
    prisma.opportunity.deleteMany(),
    prisma.contact.deleteMany(),
    prisma.company.deleteMany(),
    prisma.campaign.deleteMany(),
    prisma.refreshToken.deleteMany(),
    prisma.user.deleteMany(),
  ]);

  // 2. Hash Argon2id du mot de passe commun Bloom2026!
  const passwordHash = await argon2.hash('Bloom2026!', {
    type: argon2.argon2id,
    memoryCost: 65536,
    timeCost: 3,
    parallelism: 4,
  });

  // 3. Création des 38 collaborateurs Bloom
  const createdUsers = [];
  for (const spec of USERS_SPEC) {
    const user = await prisma.user.create({
      data: {
        email: spec.email,
        passwordHash,
        firstName: spec.firstName,
        lastName: spec.lastName,
        jobTitle: spec.jobTitle,
        role: spec.role,
        department: spec.department,
        isActive: spec.isActive,
        notifyEmailAlerts: true,
        notifyInApp: true,
      },
    });
    createdUsers.push(user);
  }

  const adminUsers = createdUsers.filter((u) => u.role === UserRole.ADMIN && u.isActive);
  const salesUsers = createdUsers.filter((u) => u.role === UserRole.SALES && u.isActive);
  const marketingUsers = createdUsers.filter((u) => u.role === UserRole.MARKETING && u.isActive);
  const projectManagers = createdUsers.filter(
    (u) => u.role === UserRole.DELIVERY && u.department === Department.PROJECT_MANAGEMENT && u.isActive
  );
  const deliveryUsers = createdUsers.filter((u) => u.role === UserRole.DELIVERY && u.isActive);

  // 4. Création des 6 campagnes marketing (budgets 35 k€ - 65 k€ pour ROI crédibles 400%-1100%)
  const campaignsData = [
    {
      code: 'CMP-2026-SEO-Q1',
      name: 'Audit SEO & Visibilité E-commerce B2B',
      channel: AcquisitionChannel.GOOGLE_ADS_SEO,
      targetSector: ClientSector.COMMERCE_ECOMMERCE,
      budgetHT: new Prisma.Decimal('62000.00'),
      startDate: addDays(now, -180),
      endDate: addDays(now, 90),
      isActive: true,
    },
    {
      code: 'CMP-2026-LI-EXEC',
      name: 'LinkedIn ABM Direction Marketing ETI/GE',
      channel: AcquisitionChannel.LINKEDIN_ADS,
      targetSector: ClientSector.SERVICES_ENTREPRISES,
      budgetHT: new Prisma.Decimal('64000.00'),
      startDate: addDays(now, -120),
      endDate: addDays(now, 60),
      isActive: true,
    },
    {
      code: 'CMP-2026-EMAIL-REFONTE',
      name: 'Nurturing Refonte UX/UI & Conversion',
      channel: AcquisitionChannel.EMAIL_CAMPAIGN,
      targetSector: ClientSector.COMMERCE_ECOMMERCE,
      budgetHT: new Prisma.Decimal('54000.00'),
      startDate: addDays(now, -90),
      endDate: addDays(now, 45),
      isActive: true,
    },
    {
      code: 'CMP-2026-WEB-TOURISME',
      name: 'Webinar Réservation Directe & ROAS Tourisme',
      channel: AcquisitionChannel.WEBINAR_EVENT,
      targetSector: ClientSector.TOURISME_LOISIRS,
      budgetHT: new Prisma.Decimal('58000.00'),
      startDate: addDays(now, -60),
      endDate: addDays(now, 30),
      isActive: true,
    },
    {
      code: 'CMP-2026-INBOUND-SITE',
      name: 'Formulaire Devis Express Site Vitrine Bloom',
      channel: AcquisitionChannel.INBOUND_WEB_FORM,
      targetSector: null,
      budgetHT: new Prisma.Decimal('60000.00'),
      startDate: addDays(now, -365),
      endDate: null,
      isActive: true,
    },
    {
      code: 'CMP-2025-INDUS-TMA',
      name: 'Campagne Maintenance & Cloud Industrie 2025',
      channel: AcquisitionChannel.EMAIL_CAMPAIGN,
      targetSector: ClientSector.INDUSTRIE,
      budgetHT: new Prisma.Decimal('56000.00'),
      startDate: addDays(now, -300),
      endDate: addDays(now, -30),
      isActive: false,
    },
  ];

  const campaigns = [];
  for (const camp of campaignsData) {
    const created = await prisma.campaign.create({ data: camp });
    campaigns.push(created);
  }
  const activeCampaigns = campaigns.filter((c) => c.isActive);

  // 5. Création des 80 entreprises (56 PME, 20 ETI, 4 GE ; 40/30/20/10 ; 4 internationales)
  interface SeedCompanyRecord {
    id: string;
    name: string;
    sector: ClientSector;
    size: CompanySize;
    isClient: boolean;
    isInternational: boolean;
    ownerId: string;
  }

  const internationalCountries: Record<string, string> = {
    'Bruxelles Gourmet Select': 'Belgique',
    'Geneva Luxury Retail': 'Suisse',
    'LuxTrust Advisory': 'Luxembourg',
    'London Heritage Tours': 'Royaume-Uni',
  };

  const companies: SeedCompanyRecord[] = [];
  let siretCounter = 80123450000010;

  for (const sectorSpec of SECTORS_SPEC) {
    // Construire la liste des tailles pour ce secteur
    const sizeQueue: CompanySize[] = [];
    for (const s of sectorSpec.sizes) {
      for (let k = 0; k < s.count; k += 1) {
        sizeQueue.push(s.size);
      }
    }

    for (let i = 0; i < sectorSpec.totalCompanies; i += 1) {
      const name = pick(sectorSpec.companyNames, i);
      const size = pick(sizeQueue, i);
      const isClient = i < sectorSpec.activeClients;
      const intlCountry = internationalCountries[name];
      const isInternational = intlCountry !== undefined;
      const country = intlCountry ?? 'France';
      const city = isInternational
        ? (country === 'Belgique' ? 'Bruxelles' : country === 'Suisse' ? 'Genève' : country === 'Luxembourg' ? 'Luxembourg' : 'Londres')
        : pick(sectorSpec.cities, i);
      const owner = pick(salesUsers, companies.length);
      siretCounter += 17;

      const annualRevBase = size === CompanySize.GE ? 85000000 : size === CompanySize.ETI ? 18000000 : 3200000;
      const annualRev = new Prisma.Decimal((annualRevBase + Math.round(rng() * 1500000)).toFixed(2));

      const slug = name
        .toLowerCase()
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '')
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-|-$/g, '');

      const created = await prisma.company.create({
        data: {
          name,
          siret: isInternational ? null : String(siretCounter),
          sector: sectorSpec.sector,
          size,
          website: `https://www.${slug}.${isInternational ? 'com' : 'fr'}`,
          phone: `+33 1 4${String(10 + (companies.length % 89)).padStart(2, '0')} ${String(20 + (i % 70)).padStart(2, '0')} ${String(10 + ((i * 3) % 85)).padStart(2, '0')} ${String(11 + ((i * 7) % 88)).padStart(2, '0')}`,
          address: `${12 + i} Avenue de la République`,
          city,
          postalCode: isInternational ? '1000' : `${75001 + (companies.length % 19)}`,
          country,
          isInternational,
          isClient,
          annualRevenue: annualRev,
          notes: isClient
            ? `Compte client actif (${SECTOR_LABELS_FR[sectorSpec.sector]}) suivi par ${owner.firstName} ${owner.lastName}.`
            : `Prospect qualifié par le pôle Acquisition Bloom (${SECTOR_LABELS_FR[sectorSpec.sector]}).`,
          ownerId: owner.id,
        },
      });

      companies.push({
        id: created.id,
        name: created.name,
        sector: created.sector,
        size: created.size,
        isClient: created.isClient,
        isInternational: created.isInternational,
        ownerId: owner.id,
      });
    }
  }

  // 6. Création des 160 contacts (2 par entreprise)
  interface SeedContactRecord {
    id: string;
    companyId: string;
    leadStatus: LeadStatus;
    assignedToId: string | null;
  }

  const contactsByCompany = new Map<string, SeedContactRecord[]>();
  let contactIndex = 0;
  let prospectSeq = 0;

  for (const company of companies) {
    const companyContacts: SeedContactRecord[] = [];
    const domain = company.name
      .toLowerCase()
      .normalize('NFD')
      .replace(/[\u0300-\u036f]/g, '')
      .replace(/[^a-z0-9]+/g, '')
      .slice(0, 16);

    for (let c = 0; c < 2; c += 1) {
      contactIndex += 1;
      const firstName = pick(FIRST_NAMES, contactIndex * 3 + c);
      const lastName = pick(LAST_NAMES, contactIndex * 5 + c);
      const isDecisionMaker = c === 0;
      const campaign = pick(activeCampaigns, contactIndex);
      const hasPhone = contactIndex % 5 !== 0;

      let leadStatus: LeadStatus = LeadStatus.QUALIFIED;
      let assignedToId: string | null = company.ownerId;
      let qualifiedAt: Date | null = addDays(now, -60 - (contactIndex % 90));
      let disqualifiedReason: string | null = null;

      if (!company.isClient) {
        prospectSeq += 1;
        if (prospectSeq <= 14) {
          leadStatus = LeadStatus.NEW;
          assignedToId = null;
          qualifiedAt = null;
        } else if (prospectSeq <= 28) {
          leadStatus = LeadStatus.QUALIFYING;
          assignedToId = null;
          qualifiedAt = null;
        } else if (prospectSeq <= 44) {
          leadStatus = LeadStatus.QUALIFIED;
          assignedToId = company.ownerId;
          qualifiedAt = addDays(now, -10 - (prospectSeq % 20));
        } else {
          leadStatus = LeadStatus.DISQUALIFIED;
          assignedToId = null;
          qualifiedAt = null;
          disqualifiedReason = 'Budget inférieur au seuil agence (< 5 000 € HT)';
        }
      }

      const emailPrefix = `${firstName}.${lastName}.${contactIndex}`
        .toLowerCase()
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '')
        .replace(/[^a-z0-9.]/g, '');

      const leadScore = computeLeadScore({
        leadStatus,
        seedIndex: contactIndex,
        isDecisionMaker,
        size: company.size,
        hasPhone,
      });

      const createdContact = await prisma.contact.create({
        data: {
          firstName,
          lastName,
          email: `${emailPrefix}@${domain || 'client'}.fr`,
          phone: hasPhone
            ? `+33 6 ${String(12 + (contactIndex % 80)).padStart(2, '0')} ${String(31 + (contactIndex % 60)).padStart(2, '0')} ${String(42 + (contactIndex % 50)).padStart(2, '0')} ${String(18 + (contactIndex % 70)).padStart(2, '0')}`
            : null,
          jobTitle: isDecisionMaker
            ? pick(DECISION_TITLES, contactIndex)
            : pick(NON_DECISION_TITLES, contactIndex),
          isDecisionMaker,
          leadStatus,
          leadScore,
          channel: campaign.channel,
          sourceDetail:
            leadStatus === LeadStatus.NEW
              ? 'Formulaire demande de devis site Bloom'
              : `Campagne ${campaign.code}`,
          qualifiedAt,
          disqualifiedReason,
          companyId: company.id,
          campaignId: campaign.id,
          assignedToId,
        },
      });

      companyContacts.push({
        id: createdContact.id,
        companyId: company.id,
        leadStatus: createdContact.leadStatus,
        assignedToId: createdContact.assignedToId,
      });
    }

    contactsByCompany.set(company.id, companyContacts);
  }

  // 7. Création des 100 missions WON = EXACTEMENT 3 600 000 € HT
  // Matrice exacte : 40/30/20/10 par secteur × 45/40/15 par pôle + 5% (180 000 €) international
  interface WonBucketSpec {
    sector: ClientSector;
    pole: ServicePole;
    count: number;
    totalEur: number;
    intlCount: number;
  }

  const WON_MATRIX: readonly WonBucketSpec[] = [
    // COMMERCE_ECOMMERCE : 40 missions = 1 440 000 € (40%)
    { sector: ClientSector.COMMERCE_ECOMMERCE, pole: ServicePole.MARKETING_DIGITAL, count: 18, totalEur: 648000, intlCount: 2 },
    { sector: ClientSector.COMMERCE_ECOMMERCE, pole: ServicePole.DEV_WEB_UX, count: 16, totalEur: 576000, intlCount: 1 },
    { sector: ClientSector.COMMERCE_ECOMMERCE, pole: ServicePole.MAINTENANCE_HEBERGEMENT, count: 6, totalEur: 216000, intlCount: 0 },

    // SERVICES_ENTREPRISES : 30 missions = 1 080 000 € (30%)
    { sector: ClientSector.SERVICES_ENTREPRISES, pole: ServicePole.MARKETING_DIGITAL, count: 14, totalEur: 504000, intlCount: 0 },
    { sector: ClientSector.SERVICES_ENTREPRISES, pole: ServicePole.DEV_WEB_UX, count: 12, totalEur: 432000, intlCount: 1 },
    { sector: ClientSector.SERVICES_ENTREPRISES, pole: ServicePole.MAINTENANCE_HEBERGEMENT, count: 4, totalEur: 144000, intlCount: 0 },

    // TOURISME_LOISIRS : 20 missions = 720 000 € (20%)
    { sector: ClientSector.TOURISME_LOISIRS, pole: ServicePole.MARKETING_DIGITAL, count: 9, totalEur: 324000, intlCount: 1 },
    { sector: ClientSector.TOURISME_LOISIRS, pole: ServicePole.DEV_WEB_UX, count: 8, totalEur: 288000, intlCount: 0 },
    { sector: ClientSector.TOURISME_LOISIRS, pole: ServicePole.MAINTENANCE_HEBERGEMENT, count: 3, totalEur: 108000, intlCount: 0 },

    // INDUSTRIE : 10 missions = 360 000 € (10%)
    { sector: ClientSector.INDUSTRIE, pole: ServicePole.MARKETING_DIGITAL, count: 4, totalEur: 144000, intlCount: 0 },
    { sector: ClientSector.INDUSTRIE, pole: ServicePole.DEV_WEB_UX, count: 4, totalEur: 144000, intlCount: 0 },
    { sector: ClientSector.INDUSTRIE, pole: ServicePole.MAINTENANCE_HEBERGEMENT, count: 2, totalEur: 72000, intlCount: 0 },
  ];

  const poleTitles: Record<ServicePole, readonly string[]> = {
    MARKETING_DIGITAL: [
      'Stratégie SEO & Acquisition Paid Media',
      'Campagne Social Ads & Lead Gen B2B',
      'Refonte Tunnel Emailing & CRM Automation',
      'Programme SEA / Google Shopping Performance',
    ],
    DEV_WEB_UX: [
      'Refonte Plateforme Web & Design System',
      'Création Boutique E-commerce Headless',
      'Audit UX/UI & Développement Portail Client',
      'Application Web B2B Sur-Mesure',
    ],
    MAINTENANCE_HEBERGEMENT: [
      'Contrat TMA & Infogérance Cloud Haute Dispo',
      'Maintenance Applicative & Optimisation Perf',
      'Hébergement Managé & Monitoring 24/7',
    ],
  };

  interface SeedWonOpp {
    id: string;
    reference: string;
    title: string;
    pole: ServicePole;
    amountHT: Prisma.Decimal;
    companyId: string;
    companyName: string;
    ownerId: string;
    wonAt: Date;
    commercialSummary: string;
  }

  const wonOpportunities: SeedWonOpp[] = [];
  let oppSeq = 0;
  let quoteSeq = 0;

  for (const bucket of WON_MATRIX) {
    const sectorClients = companies.filter((c) => c.sector === bucket.sector && c.isClient);
    const intlClients = sectorClients.filter((c) => c.isInternational);
    const domesticClients = sectorClients.filter((c) => !c.isInternational);

    const fixedPositions: number[] = [];
    for (let f = 0; f < bucket.intlCount; f += 1) {
      fixedPositions.push(f);
    }

    const amounts = buildExactAmounts(bucket.count, bucket.totalEur, fixedPositions);

    for (let i = 0; i < bucket.count; i += 1) {
      oppSeq += 1;
      quoteSeq += 1;
      const isIntlMission = i < bucket.intlCount;
      const targetCompany = isIntlMission
        ? pick(intlClients, i)
        : pick(domesticClients, i + oppSeq);
      const companyContacts = contactsByCompany.get(targetCompany.id) ?? [];
      const primaryContact = companyContacts[0];
      const amountVal = amounts[i] ?? 36000;
      const amountDec = new Prisma.Decimal(`${amountVal}.00`);
      const wonAt = addDays(now, -Math.floor((oppSeq * 330) / 100) - 10);
      const createdAt = addDays(wonAt, -35);
      const campaign = pick(campaigns, oppSeq);
      const title = `${pick(poleTitles[bucket.pole], oppSeq)} — ${targetCompany.name}`;
      const commercialSummary =
        `Brief validé avec ${targetCompany.name} (${SECTOR_LABELS_FR[bucket.sector]}) : accompagnement ${POLE_LABELS_FR[bucket.pole]} ` +
        `sur 12 mois avec objectifs de conversion mesurables, reporting mensuel et points bi-hebdomadaires.`;

      const opp = await prisma.opportunity.create({
        data: {
          reference: padRef('OPP', oppSeq),
          title,
          pole: bucket.pole,
          amountHT: amountDec,
          probability: 100,
          stage: OpportunityStage.WON,
          expectedCloseAt: wonAt,
          nextFollowUpAt: null,
          followUpCount: 2,
          lastContactedAt: addDays(wonAt, -2),
          wonAt,
          commercialSummary,
          companyId: targetCompany.id,
          primaryContactId: primaryContact?.id ?? null,
          ownerId: targetCompany.ownerId,
          campaignId: campaign.id,
          createdAt,
        },
      });

      await prisma.quote.create({
        data: {
          reference: padRef('DEV', quoteSeq),
          version: 1,
          amountHT: amountDec,
          vatRate: new Prisma.Decimal('20.00'),
          status: QuoteStatus.ACCEPTED,
          sentAt: addDays(wonAt, -14),
          validUntil: addDays(wonAt, 16),
          acceptedAt: wonAt,
          notes: `Devis accepté et signé électroniquement — ${targetCompany.name}`,
          opportunityId: opp.id,
        },
      });

      wonOpportunities.push({
        id: opp.id,
        reference: opp.reference,
        title: opp.title,
        pole: opp.pole,
        amountHT: amountDec,
        companyId: targetCompany.id,
        companyName: targetCompany.name,
        ownerId: targetCompany.ownerId,
        wonAt,
        commercialSummary,
      });
    }
  }

  // 8. Création des 25 opportunités en cours (dont 5 avec relance dépassée) + 5 LOST
  const openStages: readonly { stage: OpportunityStage; count: number; prob: number }[] = [
    { stage: OpportunityStage.PROSPECTION, count: 6, prob: 10 },
    { stage: OpportunityStage.QUALIFICATION, count: 6, prob: 25 },
    { stage: OpportunityStage.PROPOSAL_SENT, count: 7, prob: 50 },
    { stage: OpportunityStage.NEGOTIATION, count: 6, prob: 75 },
  ];

  const allPoles = [
    ServicePole.MARKETING_DIGITAL,
    ServicePole.DEV_WEB_UX,
    ServicePole.MAINTENANCE_HEBERGEMENT,
  ] as const;

  const prospectCompanies = companies.filter((c) => !c.isClient);
  let openIdx = 0;
  let overdueCount = 0;

  for (const stageSpec of openStages) {
    for (let j = 0; j < stageSpec.count; j += 1) {
      oppSeq += 1;
      openIdx += 1;
      const targetCompany = pick(
        openIdx % 2 === 0 ? prospectCompanies : companies,
        openIdx * 3
      );
      const companyContacts = contactsByCompany.get(targetCompany.id) ?? [];
      const primaryContact = companyContacts[0];
      const pole = pick(allPoles, openIdx);
      const amountVal = 18000 + ((openIdx * 4500) % 42000);
      const amountDec = new Prisma.Decimal(`${amountVal}.00`);

      // 5 opportunités avec nextFollowUpAt dépassée (PROPOSAL_SENT & NEGOTIATION)
      const shouldBeOverdue =
        (stageSpec.stage === OpportunityStage.PROPOSAL_SENT ||
          stageSpec.stage === OpportunityStage.NEGOTIATION) &&
        overdueCount < 5;

      let nextFollowUpAt: Date;
      if (shouldBeOverdue) {
        overdueCount += 1;
        nextFollowUpAt = addDays(now, -(2 + overdueCount * 2));
      } else {
        nextFollowUpAt = addDays(now, 3 + (openIdx % 14));
      }

      const opp = await prisma.opportunity.create({
        data: {
          reference: padRef('OPP', oppSeq),
          title: `${pick(poleTitles[pole], openIdx)} — ${targetCompany.name}`,
          pole,
          amountHT: amountDec,
          probability: stageSpec.prob,
          stage: stageSpec.stage,
          expectedCloseAt: addDays(now, 15 + (openIdx % 45)),
          nextFollowUpAt,
          followUpCount: stageSpec.stage === OpportunityStage.PROPOSAL_SENT ? 1 : 0,
          lastContactedAt: addDays(now, -5),
          commercialSummary:
            stageSpec.stage === OpportunityStage.NEGOTIATION
              ? 'Atelier de cadrage réalisé, validation juridique et planning en cours.'
              : null,
          companyId: targetCompany.id,
          primaryContactId: primaryContact?.id ?? null,
          ownerId: targetCompany.ownerId,
          campaignId: pick(activeCampaigns, openIdx).id,
        },
      });

      if (
        stageSpec.stage === OpportunityStage.PROPOSAL_SENT ||
        stageSpec.stage === OpportunityStage.NEGOTIATION
      ) {
        quoteSeq += 1;
        await prisma.quote.create({
          data: {
            reference: padRef('DEV', quoteSeq),
            version: 1,
            amountHT: amountDec,
            vatRate: new Prisma.Decimal('20.00'),
            status: QuoteStatus.SENT,
            sentAt: addDays(now, -9),
            validUntil: addDays(now, 21),
            notes: 'Proposition commerciale détaillée envoyée par email.',
            opportunityId: opp.id,
          },
        });
      }
    }
  }

  // 5 opportunités LOST
  const lostReasons = [
    'Choix d’une agence locale concurrente',
    'Report du projet au prochain exercice budgétaire',
    'Internalisation de la compétence marketing',
    'Arbitrage tarifaire défavorable',
    'Changement de direction chez le prospect',
  ] as const;

  for (let l = 0; l < 5; l += 1) {
    oppSeq += 1;
    const targetCompany = pick(prospectCompanies, l + 10);
    const pole = pick(allPoles, l);
    const lostAt = addDays(now, -(15 + l * 12));

    await prisma.opportunity.create({
      data: {
        reference: padRef('OPP', oppSeq),
        title: `${pick(poleTitles[pole], l)} — ${targetCompany.name}`,
        pole,
        amountHT: new Prisma.Decimal(`${22000 + l * 5000}.00`),
        probability: 0,
        stage: OpportunityStage.LOST,
        expectedCloseAt: lostAt,
        lostAt,
        lostReason: pick(lostReasons, l),
        companyId: targetCompany.id,
        ownerId: targetCompany.ownerId,
        campaignId: pick(campaigns, l).id,
      },
    });
  }

  // 9. Création de 25 Projets (15 actifs : 3 HANDOVER_PENDING + 12 IN_PROGRESS ; + 10 COMPLETED)
  const devAndMarketingOpps = wonOpportunities.filter(
    (o) => o.pole === ServicePole.DEV_WEB_UX || o.pole === ServicePole.MARKETING_DIGITAL
  );

  const createdProjects: { id: string; reference: string; name: string; status: ProjectStatus; companyId: string }[] = [];

  for (let p = 0; p < 25; p += 1) {
    const opp = devAndMarketingOpps[p];
    if (!opp) break;

    const projectSeq = p + 1;
    let status: ProjectStatus;
    let handoverValidatedAt: Date | null = null;
    let projectManagerId: string | null = null;
    let startDate: Date | null = null;
    let deadline: Date | null = null;
    let completedAt: Date | null = null;
    let performanceMetrics: Prisma.InputJsonValue | undefined;
    let performanceSummary: string | null = null;

    if (p < 3) {
      // 3 projets en attente de validation handover pour la soutenance
      status = ProjectStatus.HANDOVER_PENDING;
      projectManagerId = pick(projectManagers, p).id;
      deadline = addDays(now, 75 + p * 15);
    } else if (p < 15) {
      // 12 projets en cours
      status = ProjectStatus.IN_PROGRESS;
      handoverValidatedAt = addDays(now, -(15 + p * 3));
      projectManagerId = pick(projectManagers, p).id;
      startDate = addDays(handoverValidatedAt, 2);
      deadline = addDays(now, 30 + p * 7);
      performanceMetrics =
        opp.pole === ServicePole.MARKETING_DIGITAL
          ? { roas: 3.8 + (p % 3) * 0.4, leadsGenerated: 140 + p * 15, cplEur: 28, ctrPct: 2.9 }
          : { lighthouseScore: 93 + (p % 6), sprintVelocity: 34, testCoveragePct: 88, uptimePct: 99.95 };
      performanceSummary = 'Avancement conforme au rétroplanning, jalons intermédiaires validés.';
    } else {
      // 10 projets terminés avec bilan complet
      status = ProjectStatus.COMPLETED;
      handoverValidatedAt = addDays(opp.wonAt, 3);
      projectManagerId = pick(projectManagers, p).id;
      startDate = addDays(opp.wonAt, 5);
      deadline = addDays(opp.wonAt, 95);
      completedAt = addDays(opp.wonAt, 90);
      performanceMetrics =
        opp.pole === ServicePole.MARKETING_DIGITAL
          ? { roas: 4.6, leadsGenerated: 410, organicTrafficGrowthPct: 64, conversionRatePct: 3.7 }
          : { lighthouseScore: 98, conversionLiftPct: 27, loadTimeMs: 680, uptimePct: 99.98 };
      performanceSummary = 'Projet livré dans le budget et les délais, KPIs cibles dépassés.';
    }

    const project = await prisma.project.create({
      data: {
        reference: padRef('PRJ', projectSeq),
        name: opp.title,
        pole: opp.pole,
        status,
        clientBrief: opp.commercialSummary,
        targetKpis:
          opp.pole === ServicePole.MARKETING_DIGITAL
            ? 'ROAS >= 4.0, +45% de leads qualifiés MQL sur 6 mois, CPL < 32 € HT'
            : 'Score Lighthouse >= 95/100, taux de conversion +25%, accessibilité RGAA AA',
        deliverablesScope:
          opp.pole === ServicePole.MARKETING_DIGITAL
            ? 'Audit sémantique, setup tracking GA4/GTM, 12 landing pages, pilotage campagnes Paid & SEO'
            : 'Maquettes Figma validées, développement front/back, recette fonctionnelle, mise en production',
        handoverValidatedAt,
        performanceMetrics,
        performanceSummary,
        budgetHT: opp.amountHT,
        startDate,
        deadline,
        completedAt,
        companyId: opp.companyId,
        opportunityId: opp.id,
        projectManagerId,
      },
    });

    createdProjects.push({
      id: project.id,
      reference: project.reference,
      name: project.name,
      status: project.status,
      companyId: project.companyId,
    });
  }

  // 10. Création de 12 Tickets Support sur les projets actifs/livrés
  const ticketSubjects = [
    'Ajustement tracking conversion GA4 checkout',
    'Optimisation temps de chargement mobile LCP',
    'Mise à jour certificat SSL & redirections 301',
    'Demande d’évolution bannière campagne printemps',
    'Synchronisation flux catalogue Google Merchant',
    'Correction affichage Safari iOS sur fiche produit',
  ] as const;

  const activeOrDoneProjects = createdProjects.filter((p) => p.status !== ProjectStatus.HANDOVER_PENDING);
  for (let t = 0; t < 12; t += 1) {
    const project = pick(activeOrDoneProjects, t);
    const assignee = pick(deliveryUsers, t + 3);
    const priorities = [TicketPriority.LOW, TicketPriority.MEDIUM, TicketPriority.HIGH, TicketPriority.URGENT] as const;
    const statuses = [TicketStatus.OPEN, TicketStatus.IN_PROGRESS, TicketStatus.WAITING_CLIENT, TicketStatus.RESOLVED] as const;
    const status = pick(statuses, t);

    await prisma.supportTicket.create({
      data: {
        reference: padRef('TCK', t + 1),
        subject: `${pick(ticketSubjects, t)} (${project.reference})`,
        description: 'Ticket remonté par le client via le portail de suivi Bloom. Analyse technique et correctif planifiés.',
        priority: pick(priorities, t),
        status,
        slaDeadline: addDays(now, status === TicketStatus.RESOLVED ? -2 : 2 + (t % 5)),
        resolvedAt: status === TicketStatus.RESOLVED ? addDays(now, -1) : null,
        resolutionNote: status === TicketStatus.RESOLVED ? 'Correctif déployé et validé en pré-production puis production.' : null,
        projectId: project.id,
        assignedToId: assignee.id,
      },
    });
  }

  // 11. Création des 20 Contrats récurrents (4 en ALERT_TRIGGERED < 45j, 2 prêts pour cron, 12 ACTIVE, 2 autres)
  const maintenanceAndMarketingOpps = [
    ...wonOpportunities.filter((o) => o.pole === ServicePole.MAINTENANCE_HEBERGEMENT),
    ...wonOpportunities.filter((o) => o.pole === ServicePole.MARKETING_DIGITAL),
  ];

  for (let c = 0; c < 20; c += 1) {
    const opp = maintenanceAndMarketingOpps[c];
    if (!opp) break;

    const alertLeadDays = 60;
    let endDate: Date;
    let renewalStatus: RenewalStatus;
    let npsScore: number | null = null;
    let csatScore: number | null = null;
    let performanceRecap: string | null = null;
    let renewalProposalSentAt: Date | null = null;

    if (c < 4) {
      // 4 contrats arrivant à échéance dans moins de 45 jours -> ALERT_TRIGGERED
      const daysRemaining = 14 + c * 9; // 14, 23, 32, 41 jours
      endDate = addDays(now, daysRemaining);
      renewalStatus = RenewalStatus.ALERT_TRIGGERED;
      npsScore = 8 + (c % 3); // 8, 9, 10
      csatScore = 4 + (c % 2); // 4, 5
      performanceRecap = `Bilan annuel positif : +42% de trafic qualifié, disponibilité 99.97%, ROAS moyen 4.3x.`;
    } else if (c < 6) {
      // 2 contrats ACTIVE dont alertTriggerDate <= now (J+48 et J+54) pour démonstration du job cron
      endDate = addDays(now, 48 + (c - 4) * 6);
      renewalStatus = RenewalStatus.ACTIVE;
      npsScore = 8;
      csatScore = 4;
      performanceRecap = 'Prestation nominale sur les 10 derniers mois, prêt pour bilan de renouvellement.';
    } else if (c < 18) {
      // 12 contrats ACTIVE avec échéance > 90 jours
      endDate = addDays(now, 105 + c * 14);
      renewalStatus = RenewalStatus.ACTIVE;
      npsScore = 7 + (c % 4);
      csatScore = 4 + (c % 2);
      performanceRecap = 'Suivi trimestriel conforme aux SLA contractuels.';
    } else if (c === 18) {
      endDate = addDays(now, 25);
      renewalStatus = RenewalStatus.PROPOSAL_SENT;
      npsScore = 9;
      csatScore = 5;
      renewalProposalSentAt = addDays(now, -6);
      performanceRecap = 'Proposition de reconduction +15% périmètre SEO envoyée au client.';
    } else {
      endDate = addDays(now, 365);
      renewalStatus = RenewalStatus.RENEWED;
      npsScore = 10;
      csatScore = 5;
      renewalProposalSentAt = addDays(now, -25);
      performanceRecap = 'Contrat reconduit pour 12 mois supplémentaires.';
    }

    const startDate = addDays(endDate, -365);
    const alertTriggerDate = addDays(endDate, -alertLeadDays);

    await prisma.contract.create({
      data: {
        reference: padRef('CTR', c + 1),
        title: `Contrat Annuel ${opp.pole === ServicePole.MAINTENANCE_HEBERGEMENT ? 'TMA & Infogérance' : 'Accompagnement Growth'} — ${opp.companyName}`,
        pole: opp.pole,
        annualValueHT: opp.amountHT,
        startDate,
        endDate,
        alertLeadDays,
        alertTriggerDate,
        renewalStatus,
        autoRenew: c % 4 === 0,
        npsScore,
        csatScore,
        performanceRecap,
        renewalProposalSentAt,
        companyId: opp.companyId,
        opportunityId: opp.id,
        ownerId: opp.ownerId,
      },
    });
  }

  // 12. Activités réalistes (2 à 3 par entreprise)
  const activityTypes = [ActivityType.CALL, ActivityType.EMAIL, ActivityType.MEETING, ActivityType.NOTE] as const;
  for (let idx = 0; idx < companies.length; idx += 1) {
    const company = companies[idx];
    if (!company) continue;
    const companyContacts = contactsByCompany.get(company.id) ?? [];
    const primaryContact = companyContacts[0];
    const actCount = company.isClient ? 3 : 2;

    for (let a = 0; a < actCount; a += 1) {
      const actType = pick(activityTypes, idx + a);
      await prisma.activity.create({
        data: {
          type: actType,
          subject:
            actType === ActivityType.MEETING
              ? `Point stratégique trimestriel — ${company.name}`
              : actType === ActivityType.CALL
                ? `Appel de suivi commercial — ${company.name}`
                : actType === ActivityType.EMAIL
                  ? `Envoi compte-rendu & prochaines étapes — ${company.name}`
                  : `Note interne qualification compte ${company.name}`,
          content: `Échange consigné par le pôle commercial Bloom concernant les priorités digitales (${SECTOR_LABELS_FR[company.sector]}).`,
          occurredAt: addDays(now, -(a * 12 + (idx % 18) + 1)),
          authorId: company.ownerId,
          companyId: company.id,
          contactId: primaryContact?.id ?? null,
        },
      });
    }
  }

  // 13. Notifications de démonstration pour les 4 profils principaux
  const demoNotifications: {
    userId: string;
    type: string;
    title: string;
    message: string;
    actionUrl: string;
  }[] = [
    {
      userId: salesUsers[0]!.id,
      type: 'QUOTE_FOLLOWUP',
      title: 'Relance devis en retard',
      message: '5 opportunités ont dépassé la date cible de relance commerciale.',
      actionUrl: '/sales/pipeline?filter=overdue',
    },
    {
      userId: salesUsers[0]!.id,
      type: 'CONTRACT_RENEWAL',
      title: 'Alerte renouvellement J-60',
      message: '4 contrats clients arrivent à échéance dans moins de 45 jours.',
      actionUrl: '/retention/contracts',
    },
    {
      userId: projectManagers[0]!.id,
      type: 'PROJECT_HANDOVER',
      title: '3 briefs commerciaux à valider',
      message: 'Des opportunités signées (WON) attendent la validation Delivery pour démarrer.',
      actionUrl: '/delivery/projects?status=HANDOVER_PENDING',
    },
    {
      userId: marketingUsers[0]!.id,
      type: 'LEAD_ASSIGNED',
      title: '14 nouveaux leads entrants à qualifier',
      message: 'De nouveaux prospects issus des campagnes web attendent votre qualification.',
      actionUrl: '/acquisition/leads?status=NEW',
    },
    {
      userId: adminUsers[0]!.id,
      type: 'CONTRACT_RENEWAL',
      title: 'Revue mensuelle portefeuille Bloom',
      message: 'CA annuel consolidé à 3 600 000 € HT sur 100 missions clients.',
      actionUrl: '/dashboard',
    },
  ];

  for (const notif of demoNotifications) {
    await prisma.notification.create({ data: notif });
  }

  // 14. AuditLogs initiaux
  await prisma.auditLog.create({
    data: {
      entityType: 'System',
      entityId: 'bloom-crm-seed',
      action: AuditAction.CREATE,
      newValues: {
        users: createdUsers.length,
        companies: companies.length,
        wonMissions: wonOpportunities.length,
        totalWonRevenueHT: '3600000.00',
      },
      actorId: adminUsers[0]!.id,
    },
  });

  // 15. Vérification & Rapport console
  const totalWonAmount = wonOpportunities.reduce((sum, o) => sum + Number(o.amountHT), 0);
  const byPole = {
    MARKETING_DIGITAL: wonOpportunities
      .filter((o) => o.pole === ServicePole.MARKETING_DIGITAL)
      .reduce((s, o) => s + Number(o.amountHT), 0),
    DEV_WEB_UX: wonOpportunities
      .filter((o) => o.pole === ServicePole.DEV_WEB_UX)
      .reduce((s, o) => s + Number(o.amountHT), 0),
    MAINTENANCE_HEBERGEMENT: wonOpportunities
      .filter((o) => o.pole === ServicePole.MAINTENANCE_HEBERGEMENT)
      .reduce((s, o) => s + Number(o.amountHT), 0),
  };

  console.log('✅ Seed Bloom CRM terminé avec succès :');
  console.log(`   • Collaborateurs : ${createdUsers.length} (actifs CRM: ${createdUsers.filter((u) => u.isActive).length})`);
  console.log(`   • Campagnes : ${campaigns.length}`);
  console.log(
    `   • Entreprises : ${companies.length} (PME: ${companies.filter((c) => c.size === CompanySize.PME).length}, ` +
      `ETI: ${companies.filter((c) => c.size === CompanySize.ETI).length}, ` +
      `GE: ${companies.filter((c) => c.size === CompanySize.GE).length}, ` +
      `Clients actifs: ${companies.filter((c) => c.isClient).length}, ` +
      `International: ${companies.filter((c) => c.isInternational).length})`
  );
  console.log(`   • Contacts : ${contactIndex}`);
  console.log(`   • Missions WON : ${wonOpportunities.length} — Total CA HT : ${totalWonAmount.toLocaleString('fr-FR')} €`);
  console.log(
    `     ↳ Marketing: ${byPole.MARKETING_DIGITAL.toLocaleString('fr-FR')} € (45%) | ` +
      `Dev/UX: ${byPole.DEV_WEB_UX.toLocaleString('fr-FR')} € (40%) | ` +
      `Maintenance: ${byPole.MAINTENANCE_HEBERGEMENT.toLocaleString('fr-FR')} € (15%)`
  );
  console.log(`   • Projets : ${createdProjects.length} (3 HANDOVER_PENDING, 12 IN_PROGRESS, 10 COMPLETED)`);
  console.log('   • Contrats : 20 (4 ALERT_TRIGGERED, 2 prêts pour cron, 12 ACTIVE, 1 PROPOSAL_SENT, 1 RENEWED)');
}

main()
  .catch((error: unknown) => {
    console.error('❌ Erreur lors du seed Bloom CRM :', error);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
