import { createDBPool } from "./src/internal/datastore/index";
import * as dotenv from "dotenv";
import path from "path";
import { sql } from "kysely";
dotenv.config({ path: path.resolve(process.cwd(), '../../.env') });

const config = {
  host: process.env.DATABASE_HOST,
  port: parseInt(process.env.DATABASE_PORT || "5432"),
  database: process.env.DATABASE_NAME,
  user: process.env.DATABASE_USER,
  password: process.env.DATABASE_PWD,
  ssl:
    process.env.DATABASE_HOST !== "localhost" &&
    process.env.DATABASE_HOST !== "127.0.0.1"
      ? { rejectUnauthorized: false }
      : undefined,
};

const migrationsToRestore = [
  { name: '20260209143500_create_campaigns_table', timestamp: '2026-02-12T05:36:33.449Z' },
  { name: '20260210154000_add_stats_to_campaigns', timestamp: '2026-02-12T05:36:33.515Z' },
  { name: '20260211131500_create_campaign_recipients_table', timestamp: '2026-02-12T05:36:33.804Z' },
  { name: '000032_admin_console_users', timestamp: '2026-02-08T00:00:00Z' },
  { name: '20260212094000_create_admin_sessions', timestamp: '2026-02-13T00:00:00Z' },
  { name: '20260214000000_console_users', timestamp: '2026-02-20T04:09:32.577Z' },
  { name: '20260214000001_console_user_sessions', timestamp: '2026-02-20T04:09:32.697Z' },
  { name: '20260215000000_chatbot_tables_add_admin_log', timestamp: '2026-03-05T08:36:30.608Z' },
  { name: '20260311000000_console_roles', timestamp: '2026-03-11T08:53:12.384Z' },
  { name: '20260311000001_seed_console_features', timestamp: '2026-03-11T09:36:34.502Z' },
  { name: '20260311000002_seed_chatbot_console_features', timestamp: '2026-03-11T09:59:29.855Z' },
  { name: '20260311000003_seed_notification_feature', timestamp: new Date().toISOString() }
];

async function restore() {
  const db = createDBPool(config);
  try {
    // 1. Create tables
    await sql`CREATE TABLE IF NOT EXISTS kysely_migration (name varchar(255) primary key, timestamp varchar(255) not null)`.execute(db);
    await sql`CREATE TABLE IF NOT EXISTS kysely_migration_lock (id varchar(255) primary key, is_locked int not null default 0)`.execute(db);
    
    // 2. Insert initial lock row
    await sql`INSERT INTO kysely_migration_lock (id, is_locked) VALUES ('migration_lock', 0) ON CONFLICT DO NOTHING`.execute(db);

    // 3. Clear existing migrations just to be safe (if any exist)
    await sql`DELETE FROM kysely_migration`.execute(db);

    // 4. Insert restored records
    for (const m of migrationsToRestore) {
      console.log(`Restoring migration ${m.name}...`);
      await sql`INSERT INTO kysely_migration (name, timestamp) VALUES (${m.name}, ${m.timestamp})`.execute(db);
    }
    
    console.log("Successfully restored kysely_migration table!");
  } catch (e) {
    console.error(e);
  } finally {
    await db.destroy();
  }
}

restore();
