import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  console.log('Adding contract categories...');

  // Create contract categories (matching existing enum values)
  const contractCategories = [
    { code: 'ELECTRICITY', name: 'Strom', icon: 'Zap', color: '#FFC107', sortOrder: 1 },
    { code: 'GAS', name: 'Gas', icon: 'Flame', color: '#FF5722', sortOrder: 2 },
    { code: 'DSL', name: 'DSL', icon: 'Wifi', color: '#2196F3', sortOrder: 3 },
    { code: 'FIBER', name: 'Glasfaser', icon: 'Cable', color: '#9C27B0', sortOrder: 4 },
    { code: 'MOBILE', name: 'Mobilfunk', icon: 'Smartphone', color: '#4CAF50', sortOrder: 5 },
    { code: 'TV', name: 'TV', icon: 'Tv', color: '#E91E63', sortOrder: 6 },
    { code: 'CAR_INSURANCE', name: 'KFZ-Versicherung', icon: 'Car', color: '#607D8B', sortOrder: 7 },
  ];

  for (const category of contractCategories) {
    await prisma.contractCategory.upsert({
      where: { code: category.code },
      update: { name: category.name, icon: category.icon, color: category.color, sortOrder: category.sortOrder },
      create: category,
    });
    console.log(`Created/updated category: ${category.name}`);
  }

  // Update existing contracts to link to their categories
  console.log('Linking existing contracts to categories...');

  for (const category of contractCategories) {
    const cat = await prisma.contractCategory.findUnique({ where: { code: category.code } });
    if (cat) {
      const result = await prisma.contract.updateMany({
        where: {
          type: category.code as any,
          contractCategoryId: null,
        },
        data: {
          contractCategoryId: cat.id,
        },
      });
      if (result.count > 0) {
        console.log(`Linked ${result.count} ${category.name} contracts`);
      }
    }
  }

  console.log('Contract categories setup completed!');
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
