import { PrismaClient, Role, User } from '@prisma/client';
import * as fs from 'fs';
import * as bcrypt from 'bcrypt'
import { parse } from 'csv-parse';

const prisma = new PrismaClient();

async function parseCSV(filePath: string, columns: string[]): Promise<any[]> {
  return new Promise((resolve, reject) => {
    const parser = fs.createReadStream(filePath).pipe(parse({
      columns: columns,
      skip_empty_lines: true,
      from_line: 2,
    }));

    const result: any[] = [];
    parser.on('data', (data) => result.push(data));
    parser.on('end', () => resolve(result));
    parser.on('error', (error) => reject(error));
  });
}

async function importData() {

  const hashedPass = bcrypt.hashSync('adminFrApp', 10);

  const data = {
    nume: 'Admin',
    prenume: 'Admin',
    email: 'admin@gmail.com',
    password: hashedPass,
    role: Role.COORDONATOR,
  };

  await prisma.user.create({ data })

  const user: User[] = await prisma.user.findMany();
  const userId: string = user[0].id;

  const eventsFilePath = './prisma/events.csv'
  const companiesFilePath = './prisma/companies.csv'
  const contractsFilePath = './prisma/contracts.csv'

  const [events, companies, contracts] = await Promise.all([
    parseCSV(eventsFilePath, ['name', 'year', 'drive']),
    parseCSV(companiesFilePath, ['companyName', 'category', 'description', 'contactName', 'contactEmail', 'contactPhone', 'contactLinkedIn', 'contactFacebook', 'contactRole', 'contactIsActive', 'contactIsPrimary', 'contactNotes']),
    parseCSV(contractsFilePath, ['companyName', 'eventName', 'eventYear', 'status', 'notes']),
  ]);

  // Insert companies and their networks
  const companyPromises = companies.map(async (company) => {
    const existingCompany = await prisma.company.findFirst({
      where: {name: company.companyName}
    })

    if (existingCompany) {
      await prisma.network.create({
        data: {
          companyID: existingCompany.id,
          name: company.contactName,
          email: company.contactEmail,
          phone: company.contactPhone,
          linkedIn: company.contactLinkedIn,
          facebook: company.contactFacebook,
          role: company.contactRole,
          isActive: company.contactIsActive === 'TRUE',
          isPrimary: company.contactIsPrimary === 'TRUE',
          notes: company.contactNotes,
        }
      })
      return existingCompany;
    } else {
        const createdCompany = await prisma.company.create({
          data: {
            name: company.companyName,
          // category: company.category,
          description: company.description,
          networks: {
            create: {
              name: company.contactName,
              email: company.contactEmail,
              phone: company.contactPhone,
              linkedIn: company.contactLinkedIn,
              facebook: company.contactFacebook,
              role: company.contactRole,
              isActive: company.contactIsActive === 'TRUE',
              isPrimary: company.contactIsPrimary === 'TRUE',
              notes: company.contactNotes,
            }
          }
        }
      });
      return createdCompany;
    }
  });
  
  const createdCompanies = await Promise.all(companyPromises);

  // Insert events
  const eventPromises = events.map(async (eventData) => {
    const createdEvent = await prisma.event.create({
      data: {
        name: eventData.name,
        year: eventData.year,
        drive: eventData.drive,
        mdID: userId,
        contracts: { create: [] }
      }
    });
    return createdEvent;
  });

  const createdEvents = await Promise.all(eventPromises);

  // Map to easily find created IDs
  const companyMap = new Map(createdCompanies.map(company => [company.name, company.id]));
  const eventMap = new Map(createdEvents.map(event => [event.name + event.year, event.id]));

  // Insert contracts
  const contractPromises = contracts.map(async (contract) => {
    const companyId = companyMap.get(contract.companyName);
    const eventId = eventMap.get(contract.eventName + contract.eventYear);

    if (!companyId || !eventId) {
      throw new Error(`Company or Event not found for contract: ${JSON.stringify(contract)}`);
    }

    const createdContract = await prisma.contract.create({
      data: {
        companyID: companyId,
        eventID: eventId,
        userID: userId,
        status: contract.status,
        notes: contract.notes
      }
    });
    return createdContract;
  });

  await Promise.all(contractPromises);
}

// Call the import function
importData().then(() => {
  console.log('Data imported successfully.');
  prisma.$disconnect()
}).catch(error => {
  console.error('Error importing data:', error);
});

what is wrong with the import companies part