import 'dotenv/config';
import { readFileSync } from 'node:fs';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '../src/generated/prisma/client';
import { validateIssueMatrixSeedTarget } from './seeds/issue-matrix.seed';
import { seedIssueProgress } from './seeds/issue-progress.seed';

export function parseIssueProgressArgs(args: string[]) {
  const seen = new Set<string>();
  let file: string | undefined;
  let database: string | undefined;
  let apply = false;
  for (const arg of args) {
    const key = arg.split('=')[0];
    if (seen.has(key)) throw new Error(`Repeated option: ${key}`);
    seen.add(key);
    if (arg === '--apply') apply = true;
    else if (arg.startsWith('--file=') && arg.length > 7) file = arg.slice(7);
    else if (arg.startsWith('--database=') && arg.length > 11)
      database = arg.slice(11);
    else throw new Error('Use --file=PATH, --apply and --database=NAME only');
  }
  if (!file)
    throw new Error(
      '--file=PATH is required; there is no enabled default source',
    );
  return { file, database, apply };
}

async function main() {
  const args = parseIssueProgressArgs(process.argv.slice(2));
  const source: unknown = JSON.parse(readFileSync(args.file, 'utf8'));
  const connectionString = process.env.DATABASE_URL;
  if (!connectionString) throw new Error('DATABASE_URL is missing');
  const target = validateIssueMatrixSeedTarget(connectionString, args.database);
  const prisma = new PrismaClient({
    adapter: new PrismaPg({ connectionString }),
  });
  try {
    console.log(
      JSON.stringify(
        { target, ...(await seedIssueProgress(prisma, source, args.apply)) },
        null,
        2,
      ),
    );
  } finally {
    await prisma.$disconnect();
  }
}

if (require.main === module) {
  main().catch((error: Error) => {
    console.error(error.message);
    process.exitCode = 1;
  });
}
