import { auth } from '@lib/auth';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '../src/generated/prisma/client.js';
import { settingsData, userData } from './data.js';

const adapter = new PrismaPg({
  connectionString: process.env.DATABASE_URL!,
});

const prisma = new PrismaClient({ adapter });

async function main() {
  console.log('🌱 Seeding database...');
  let admin;

  // check mail exists
  const mailExists = await prisma.user.findFirst({
    where: {
      email: 'luu.dat.tham@gmail.com',
    },
  });
  if (!mailExists) {
    // add admin user
    admin = await auth.api.createUser({
      body: {
        email: 'luu.dat.tham@gmail.com',
        password: 'Th@m!S@m!040390',
        name: 'Sam Liu',
        role: 'admin',
      },
    });
  }

  console.log('---------------Created admin user-----------------');

  userData.map(async (user) => {
    await auth.api.createUser({
      body: {
        email: user.email,
        password: 'Th@m!S@m!040390',
        name: user.name,
        role: 'user',
      },
    });
  });

  console.log('---------------Created member user-----------------');
  await prisma.setting.deleteMany();

  const listSettings = [
    ...settingsData,
    {
      key: admin ? (admin?.user?.id as string) : (mailExists?.id as string),
      value: '{"language": "en"}',
      description: 'User settings',
      relation: 'user',
    },
  ];

  await prisma.setting.createMany({
    data: listSettings,
    skipDuplicates: true,
  });
  console.log('---------------Created settings-----------------');
}

main()
  .catch((e) => {
    console.error('❌ Error seeding database:', e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
