import { PrismaClient, Prisma, UserRole, CommissionScope, MovementType } from '@prisma/client'
import argon2 from 'argon2'

const prisma = new PrismaClient()

async function hashPassword(plain: string): Promise<string> {
  return argon2.hash(plain, { type: argon2.argon2id, memoryCost: 65536, timeCost: 3, parallelism: 1 })
}

async function main(): Promise<void> {
  console.log('🌱 Iniciando seed...')

  // ── Usuarios ──────────────────────────────────────────────────────────────
  const adminHash = await hashPassword('Admin2025!')
  const admin = await prisma.user.upsert({
    where: { email: 'admin@boutique.co' },
    update: {},
    create: {
      fullName: 'María Rodríguez',
      email: 'admin@boutique.co',
      passwordHash: adminHash,
      role: UserRole.admin,
      discountLimitPct: 100,
    },
  })

  const sellerHash = await hashPassword('Vendedor2025!')
  const seller = await prisma.user.upsert({
    where: { email: 'vendedor@boutique.co' },
    update: {},
    create: {
      fullName: 'Carlos Pérez',
      email: 'vendedor@boutique.co',
      passwordHash: sellerHash,
      role: UserRole.seller,
      discountLimitPct: 10,
    },
  })

  console.log(`  ✓ Admin: ${admin.email}`)
  console.log(`  ✓ Vendedor: ${seller.email}`)

  // ── Categorías ────────────────────────────────────────────────────────────
  const catRopa = await prisma.category.upsert({
    where: { name: 'Ropa de mujer' },
    update: {},
    create: { name: 'Ropa de mujer', isActive: true },
  })

  const catAccesorios = await prisma.category.upsert({
    where: { name: 'Accesorios' },
    update: {},
    create: { name: 'Accesorios', isActive: true },
  })

  console.log(`  ✓ Categorías: ${catRopa.name}, ${catAccesorios.name}`)

  // ── Proveedores ───────────────────────────────────────────────────────────
  const sup1 = await prisma.supplier.upsert({
    where: { id: 'seed-sup-001' },
    update: {},
    create: {
      id: 'seed-sup-001',
      name: 'Confecciones Bogotá S.A.S.',
      contactName: 'Luisa Mendoza',
      phone: '3101234567',
      email: 'pedidos@confeccionesbogota.co',
      notes: 'Proveedor principal de ropa femenina. Tiempo de entrega 5 días hábiles.',
    },
  })

  const sup2 = await prisma.supplier.upsert({
    where: { id: 'seed-sup-002' },
    update: {},
    create: {
      id: 'seed-sup-002',
      name: 'Distribuidora Moda Colombia',
      contactName: 'Andrés Vargas',
      phone: '3209876543',
      email: 'ventas@modacolombia.co',
      notes: 'Accesorios y complementos. Pedido mínimo: 10 unidades por referencia.',
    },
  })

  console.log(`  ✓ Proveedores: ${sup1.name}, ${sup2.name}`)

  // ── Producto 1: Vestido floral ─────────────────────────────────────────────
  const prod1 = await prisma.product.upsert({
    where: { reference: 'VES-FLOR-001' },
    update: {},
    create: {
      categoryId: catRopa.id,
      supplierId: sup1.id,
      name: 'Vestido floral de verano',
      description: 'Vestido de tela liviana con estampado floral. Ideal para clima cálido. Cierre lateral invisible.',
      reference: 'VES-FLOR-001',
      basePrice: 120000,
      costPrice: 58000,
      isActive: true,
    },
  })

  const v1s = await prisma.productVariant.upsert({
    where: { barcode: 'VES-FLOR-001-S-ROJ' },
    update: {},
    create: {
      productId: prod1.id,
      size: 'S',
      color: 'Rojo',
      barcode: 'VES-FLOR-001-S-ROJ',
      stock: 20,
      minStock: 5,
    },
  })

  const v1m = await prisma.productVariant.upsert({
    where: { barcode: 'VES-FLOR-001-M-ROJ' },
    update: {},
    create: {
      productId: prod1.id,
      size: 'M',
      color: 'Rojo',
      barcode: 'VES-FLOR-001-M-ROJ',
      stock: 20,
      minStock: 5,
    },
  })

  // Movimientos de inventario para vestido
  await prisma.inventoryMovement.createMany({
    skipDuplicates: true,
    data: [
      {
        variantId: v1s.id,
        type: MovementType.purchase,
        quantity: 20,
        unitCost: 58000,
        userId: admin.id,
        note: 'Stock inicial seed',
      },
      {
        variantId: v1m.id,
        type: MovementType.purchase,
        quantity: 20,
        unitCost: 58000,
        userId: admin.id,
        note: 'Stock inicial seed',
      },
    ],
  })

  console.log(`  ✓ Producto: ${prod1.name} (S/Rojo x20, M/Rojo x20)`)

  // ── Producto 2: Blusa casual ──────────────────────────────────────────────
  const prod2 = await prisma.product.upsert({
    where: { reference: 'BLU-CAS-001' },
    update: {},
    create: {
      categoryId: catRopa.id,
      supplierId: sup1.id,
      name: 'Blusa casual manga corta',
      description: 'Blusa de algodón pima con cuello redondo. Lavable a máquina. Colores firmes.',
      reference: 'BLU-CAS-001',
      basePrice: 75000,
      costPrice: 33000,
      isActive: true,
    },
  })

  const v2s = await prisma.productVariant.upsert({
    where: { barcode: 'BLU-CAS-001-S-BLA' },
    update: {},
    create: {
      productId: prod2.id,
      size: 'S',
      color: 'Blanco',
      barcode: 'BLU-CAS-001-S-BLA',
      stock: 30,
      minStock: 8,
    },
  })

  const v2m = await prisma.productVariant.upsert({
    where: { barcode: 'BLU-CAS-001-M-BLA' },
    update: {},
    create: {
      productId: prod2.id,
      size: 'M',
      color: 'Blanco',
      barcode: 'BLU-CAS-001-M-BLA',
      stock: 30,
      minStock: 8,
    },
  })

  await prisma.inventoryMovement.createMany({
    skipDuplicates: true,
    data: [
      {
        variantId: v2s.id,
        type: MovementType.purchase,
        quantity: 30,
        unitCost: 33000,
        userId: admin.id,
        note: 'Stock inicial seed',
      },
      {
        variantId: v2m.id,
        type: MovementType.purchase,
        quantity: 30,
        unitCost: 33000,
        userId: admin.id,
        note: 'Stock inicial seed',
      },
    ],
  })

  console.log(`  ✓ Producto: ${prod2.name} (S/Blanco x30, M/Blanco x30)`)

  // ── Producto 3: Bolso de cuero ────────────────────────────────────────────
  const prod3 = await prisma.product.upsert({
    where: { reference: 'BOL-CUE-001' },
    update: {},
    create: {
      categoryId: catAccesorios.id,
      supplierId: sup2.id,
      name: 'Bolso cuero sintético camel',
      description: 'Bolso de hombro en cuero sintético. Compartimentos interiores con cierre. Correa ajustable.',
      reference: 'BOL-CUE-001',
      basePrice: 180000,
      costPrice: 85000,
      isActive: true,
    },
  })

  const v3u = await prisma.productVariant.upsert({
    where: { barcode: 'BOL-CUE-001-U-CAM' },
    update: {},
    create: {
      productId: prod3.id,
      size: 'Único',
      color: 'Camel',
      barcode: 'BOL-CUE-001-U-CAM',
      stock: 15,
      minStock: 3,
    },
  })

  await prisma.inventoryMovement.create({
    data: {
      variantId: v3u.id,
      type: MovementType.purchase,
      quantity: 15,
      unitCost: 85000,
      userId: admin.id,
      note: 'Stock inicial seed',
    },
  })

  console.log(`  ✓ Producto: ${prod3.name} (Único/Camel x15)`)

  // ── Regla de comisión global ──────────────────────────────────────────────
  const existingRule = await prisma.commissionRule.findFirst({
    where: { scope: CommissionScope.global, isActive: true },
  })

  if (!existingRule) {
    await prisma.commissionRule.create({
      data: {
        scope: CommissionScope.global,
        percentage: 3.0,
        isActive: true,
      },
    })
    console.log('  ✓ Regla de comisión global: 3%')
  } else {
    console.log('  ✓ Regla de comisión global: ya existía')
  }

  // ── Settings ──────────────────────────────────────────────────────────────
  const settings: Array<{ key: string; value: Prisma.InputJsonValue }> = [
    { key: 'tax.iva_rate', value: 19 },
    { key: 'currency.code', value: 'COP' },
    { key: 'currency.symbol', value: '$' },
    { key: 'currency.decimal_places', value: 0 },
    { key: 'checkout.reservation_ttl_minutes', value: 15 },
    { key: 'loyalty.points_per_cop', value: 0.001 },
    { key: 'loyalty.tier_thresholds', value: { silver: 500, gold: 2000 } },
    {
      key: 'loyalty.tier_benefits',
      value: { standard: 0, silver: 0.05, gold: 0.10 },
    },
    { key: 'store.name', value: 'Boutique' },
    { key: 'store.phone', value: '' },
    { key: 'store.address', value: '' },
  ]

  for (const s of settings) {
    await prisma.setting.upsert({
      where: { key: s.key },
      update: { value: s.value },
      create: { key: s.key, value: s.value },
    })
  }

  console.log(`  ✓ Settings: ${settings.length} entradas`)
  console.log('')
  console.log('✅ Seed completado sin errores.')
}

main()
  .catch((err: unknown) => {
    console.error('❌ Error en seed:', err)
    process.exit(1)
  })
  .finally(() => {
    void prisma.$disconnect()
  })
