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

const constraintFlags = [
  {
    flag: "--supabase-url=URL / --supabase-key=KEY",
    description: "Override Supabase RPC credentials.",
  },
  {
    flag: "--supabase-config=PATH",
    description: "Load Supabase credentials (supports database block).",
  },
];

export const constraintsCommand: CommandModule = {
  name: "constraints",
  description: "Generate constraint SQL artifacts from Supabase schema metadata.",
  flags: constraintFlags,
  handler: async ({ args }: CommandContext) => {
    const resolvedConfig = await resolveSupabaseConfig(args);
    const schemaJsonRaw = await fetchSchemaJson(resolvedConfig);
    const schemaJson = normalizeSchemaJson(schemaJsonRaw);
    await writeConstraintsFiles(schemaJson);
  },
};
