import { and, eq } from 'drizzle-orm';

import { db } from '../db/client';
import { accounts, users } from '../db/schema';

const PROVIDER_ID = 'credential';

const run = async (): Promise<void> => {
  const existingUsers = await db.select({
    id: users.id,
    passwordHash: users.passwordHash,
  }).from(users);

  let created = 0;

  for (const user of existingUsers) {
    const account = await db.query.accounts.findFirst({
      where: and(
        eq(accounts.userId, user.id),
        eq(accounts.providerId, PROVIDER_ID),
        eq(accounts.accountId, user.id),
      ),
    });

    if (account) {
      continue;
    }

    await db.insert(accounts).values({
      userId: user.id,
      accountId: user.id,
      providerId: PROVIDER_ID,
      password: user.passwordHash,
    });

    created += 1;
  }

  console.log(`Created ${created} credential account(s).`);
};

run()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error('Failed to migrate Better Auth accounts', error);
    process.exit(1);
  });
