import { d as db } from '../create-upload-progress-table/POST-C-OoiMoW.js';
import { sql } from 'drizzle-orm';
import fs from 'fs';
import path from 'path';

async function handler(req, res) {
  const results = [];
  const errors = [];
  try {
    try {
      await db.execute(sql`CREATE DATABASE IF NOT EXISTS cloudvault`);
      results.push("✓ Database created/verified");
    } catch (error) {
      errors.push(`Database creation: ${error instanceof Error ? error.message : String(error)}`);
    }
    try {
      await db.execute(sql`USE cloudvault`);
      results.push("✓ Connected to cloudvault database");
    } catch (error) {
      errors.push(`Database connection: ${error instanceof Error ? error.message : String(error)}`);
    }
    try {
      const migration0000 = fs.readFileSync(
        path.join(process.cwd(), "drizzle/0000_fancy_junta.sql"),
        "utf-8"
      );
      const statements = migration0000.split(";").filter((s) => s.trim());
      for (const statement of statements) {
        await db.execute(sql.raw(statement));
      }
      results.push("✓ Migration 0000: Initial tables created");
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error);
      if (!msg.includes("already exists")) {
        errors.push(`Migration 0000: ${msg}`);
      } else {
        results.push("✓ Migration 0000: Tables already exist");
      }
    }
    try {
      const migration0001 = fs.readFileSync(
        path.join(process.cwd(), "drizzle/0001_uneven_robin_chapel.sql"),
        "utf-8"
      );
      const statements = migration0001.split(";").filter((s) => s.trim());
      for (const statement of statements) {
        await db.execute(sql.raw(statement));
      }
      results.push("✓ Migration 0001: Backup schedules table created");
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error);
      if (!msg.includes("already exists")) {
        errors.push(`Migration 0001: ${msg}`);
      } else {
        results.push("✓ Migration 0001: Table already exists");
      }
    }
    try {
      const migration0002 = fs.readFileSync(
        path.join(process.cwd(), "drizzle/0002_blue_next_avengers.sql"),
        "utf-8"
      );
      const statements = migration0002.split(";").filter((s) => s.trim());
      for (const statement of statements) {
        await db.execute(sql.raw(statement));
      }
      results.push("✓ Migration 0002: Servers table created");
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error);
      if (!msg.includes("already exists")) {
        errors.push(`Migration 0002: ${msg}`);
      } else {
        results.push("✓ Migration 0002: Table already exists");
      }
    }
    try {
      await db.execute(sql`
        CREATE TABLE IF NOT EXISTS upload_progress (
          id INT AUTO_INCREMENT NOT NULL,
          backup_id VARCHAR(255) NOT NULL,
          device_id VARCHAR(255) NOT NULL,
          file_name VARCHAR(500) NOT NULL,
          total_chunks INT NOT NULL,
          uploaded_chunks INT DEFAULT 0,
          total_size INT,
          uploaded_size INT DEFAULT 0,
          status VARCHAR(50) DEFAULT 'uploading',
          started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          completed_at TIMESTAMP NULL,
          updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          CONSTRAINT upload_progress_id PRIMARY KEY (id),
          CONSTRAINT upload_progress_backup_id_unique UNIQUE (backup_id)
        )
      `);
      results.push("✓ Upload progress table created");
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error);
      if (!msg.includes("already exists")) {
        errors.push(`Upload progress table: ${msg}`);
      } else {
        results.push("✓ Upload progress table already exists");
      }
    }
    const tables = await db.execute(sql`SHOW TABLES`);
    const tableNames = tables.map((row) => Object.values(row)[0]);
    results.push(`✓ Total tables: ${tableNames.length}`);
    results.push(`  Tables: ${tableNames.join(", ")}`);
    res.json({
      success: errors.length === 0,
      message: errors.length === 0 ? "Database setup completed successfully!" : "Setup completed with some errors",
      results,
      errors: errors.length > 0 ? errors : void 0
    });
  } catch (error) {
    console.error("Setup failed:", error);
    res.status(500).json({
      success: false,
      error: "Setup failed",
      message: error instanceof Error ? error.message : String(error),
      results,
      errors
    });
  }
}

export { handler as h };
