import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '../src/generated/prisma/client';
import { validateIssueMatrixSeedTarget } from './seeds/issue-matrix.seed';
import {
  loadProgressReportSeedSource,
  seedProgressReports,
} from './seeds/progress-report.seed';

export function parseProgressReportSeedArgs(args: string[]) {
  let apply = false;
  let file: string | undefined;
  let database: string | undefined;
  const seen = new Set<string>();
  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 --apply, --file=PATH and optionally --database=NAME',
      );
  }
  return { apply, file, database };
}

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

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