import { describe, expect, it } from "vitest";

import { isMigrationFileName, splitSqlStatements } from "../src/db/migrate.js";

describe("splitSqlStatements", () => {
  it("splits migration SQL into standalone statements", () => {
    const sql = `
      create extension if not exists citext;
      create type user_role as enum ('admin', 'operator', 'viewer', 'technik');
      create table demo (
        id text not null,
        notes text default 'semi;colon'
      );
    `;

    expect(splitSqlStatements(sql)).toEqual([
      "create extension if not exists citext",
      "create type user_role as enum ('admin', 'operator', 'viewer', 'technik')",
      `create table demo (
        id text not null,
        notes text default 'semi;colon'
      )`
    ]);
  });

  it("keeps comments and dollar-quoted bodies from breaking the split", () => {
    const sql = `
      -- comment ; should not split
      create function demo_fn() returns text as $$
      begin
        return 'ok;';
      end;
      $$ language plpgsql;

      /* block ; comment */
      create table audit_log (id integer);
    `;

    expect(splitSqlStatements(sql)).toEqual([
      `-- comment ; should not split
      create function demo_fn() returns text as $$
      begin
        return 'ok;';
      end;
      $$ language plpgsql`,
      `/* block ; comment */
      create table audit_log (id integer)`
    ]);
  });
});

describe("isMigrationFileName", () => {
  it("accepts only regular numbered migration files", () => {
    expect(isMigrationFileName("001_initial.sql")).toBe(true);
    expect(isMigrationFileName("045_add_booking_status.sql")).toBe(true);
    expect(isMigrationFileName("._001_initial.sql")).toBe(false);
    expect(isMigrationFileName(".DS_Store")).toBe(false);
    expect(isMigrationFileName("notes.sql")).toBe(false);
  });
});
