import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { resolve } from 'node:path';
import { spawnSync } from 'node:child_process';

const repoRoot = resolve(new URL('../..', import.meta.url).pathname);
const migrationsDir = resolve(repoRoot, 'prisma/migrations');
const schemaPath = resolve(repoRoot, 'prisma/schema.prisma');
const dryRun = process.argv.includes('--dry-run');
const prismaCommand = process.platform === 'win32' ? 'npx.cmd' : 'npx';

for (const envPath of ['.env', '.env.local', 'backend/.env', 'backend/.env.local']) {
  const absolutePath = resolve(repoRoot, envPath);
  if (!existsSync(absolutePath)) {
    continue;
  }

  const content = readFileSync(absolutePath, 'utf8');
  for (const line of content.split(/\r?\n/)) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#')) {
      continue;
    }

    const separatorIndex = trimmed.indexOf('=');
    if (separatorIndex === -1) {
      continue;
    }

    const key = trimmed.slice(0, separatorIndex).trim();
    const value = trimmed.slice(separatorIndex + 1).trim();
    if (key && !(key in process.env)) {
      process.env[key] = value;
    }
  }
}

const migrations = readdirSync(migrationsDir)
  .filter((name) => /^\d+_/.test(name))
  .filter((name) => statSync(resolve(migrationsDir, name)).isDirectory())
  .sort((left, right) => left.localeCompare(right));

if (migrations.length === 0) {
  console.error('No Prisma migrations found.');
  process.exit(1);
}

console.log(`Found ${migrations.length} migrations.`);
if (dryRun) {
  migrations.forEach((migration) => console.log(`- ${migration}`));
  process.exit(0);
}

for (const migration of migrations) {
  console.log(`Marking migration as applied: ${migration}`);
  const result = spawnSync(
    prismaCommand,
    ['prisma', 'migrate', 'resolve', '--applied', migration, '--schema', schemaPath],
    {
      cwd: repoRoot,
      stdio: 'inherit',
      env: process.env,
    },
  );

  if (result.status !== 0) {
    process.exit(result.status ?? 1);
  }
}

console.log('Legacy Prisma baseline completed.');
