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']),
  ]);

  const companyNetworksMap = new Map<string, any[]>();

  companies.forEach((company) => {
    if (!companyNetworksMap.has(company.companyName)) {
      companyNetworksMap.set(company.companyName, []);
    }
    companyNetworksMap.get(company.companyName)?.push({
      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,
    });
  });

  const companyPromises = Array.from(companyNetworksMap).map(async ([companyName, networks]) => {
    const existingCompany = await prisma.company.findUnique({
      where: {name: companyName}
    });

    if (existingCompany) {
      // Update existing company with new networks
      await prisma.network.createMany({
        data: networks.map(network => ({
          …network,
          companyId: existingCompany.id,
        })),
      });
      return existingCompany;
    } else {
      // Create new company
      const createdCompany = await prisma.company.create({
        data: {
          name: companyName,
          description: companies.find(company => company.companyName === companyName)?.description,
          networks: {
            create: networks,
          }
        }
      });
      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);
});

i get the following erreo:

ype '{ name: string; }' is not assignable to type 'CompanyWhereUniqueInput'.
  Type '{ name: string; }' is not assignable to type '{ id: string; } & { id?: string | undefined; AND?: CompanyWhereInput | CompanyWhereInput[] | undefined; OR?: CompanyWhereInput[] | undefined; ... 6 more ...; networks?: NetworkListRelationFilter | undefined; }'.
    Property 'id' is missing in type '{ name: string; }' but required in type '{ id: string; }'