import type { CommandContext } from "../types.js";
import { CommandModule } from "../types.js";
import {
  resolveSupabaseConfig,
  writeDatabaseConfig,
} from "../../utils/supabase.js";
import { fetchSchemaJson, normalizeSchemaJson } from "../../utils/schema.js";
import {
  writeConstraintsFiles,
  writeSeedFiles,
} from "../../utils/file-writers.js";

const seedFlags = [
  { flag: "--sql=PATH", description: "Destination for SQL CREATE TABLE statements." },
  { flag: "--cql=PATH", description: "Destination for Cassandra CQL statements." },
  {
    flag: "--if-not-exist-table",
    description: "Wrap SQL tables in CREATE TABLE IF NOT EXISTS.",
  },
  {
    flag: "--include-constraints-sql",
    description: "Generate constraint SQL artifacts alongside the seeds.",
  },
  {
    flag: "--supabase-url=URL / --supabase-key=KEY",
    description: "Override Supabase RPC credentials.",
  },
  {
    flag: "--supabase-config=PATH",
    description: "Load Supabase credentials (supports database block).",
  },
  {
    flag: "--db-config-output=PATH",
    description: "Dump parsed database config when supplied via --supabase-config.",
  },
];

export const seedCommand: CommandModule = {
  name: "seed",
  description: "Generate SQL and CQL seed files from Supabase schema metadata.",
  flags: seedFlags,
  handler: async ({ args }: CommandContext) => {
    const resolvedConfig = await resolveSupabaseConfig(args);
    const schemaJsonRaw = await fetchSchemaJson(resolvedConfig);
    const schemaJson = normalizeSchemaJson(schemaJsonRaw);
    await writeSeedFiles(schemaJson, {
      sqlPath: args.sql,
      cqlPath: args.cql,
      ifNotExists: args.ifNotExistTable,
    });
    if (args.includeConstraints) {
      await writeConstraintsFiles(schemaJson);
    }
    if (args.dbConfigOutput) {
      if (resolvedConfig.databaseConfig) {
        await writeDatabaseConfig(args.dbConfigOutput, resolvedConfig.databaseConfig);
      } else {
        console.warn("No database config available from Supabase config");
      }
    }
  },
};
