import { NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { eq, sql } from "@fitai/database";
import { db, users as usersTable, gyms as gymsTable } from "@fitai/database";
import { ensureUserSynced } from "@/lib/sync-user";
import { getDatabase } from "@/lib/database";
import log from "@/lib/logger";

async function ensureGymsTable() {
  await db.run(sql`
    CREATE TABLE IF NOT EXISTS gyms (
      id TEXT PRIMARY KEY,
      name TEXT NOT NULL,
      location TEXT,
      status TEXT NOT NULL CHECK (status IN ('active','inactive')) DEFAULT 'active',
      admin_user_id TEXT NOT NULL,
      created_at INTEGER NOT NULL,
      updated_at INTEGER NOT NULL
    )
  `);
}

// DELETE /api/gyms/[id]
// Delete a gym (soft delete - mark as inactive)
export async function DELETE(
  request: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const { id: gymId } = await params;
    const { userId } = await auth();

    if (!userId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const appDb = await getDatabase();
    const currentUser = await ensureUserSynced(userId, appDb);

    // Only superAdmin can delete gyms
    if (!currentUser || currentUser.role !== "superAdmin") {
      return NextResponse.json(
        { error: "Forbidden - Only superAdmin can delete gyms" },
        { status: 403 },
      );
    }

    await ensureGymsTable();

    // Check if gym exists using Drizzle ORM
    const existingGym = await db
      .select()
      .from(gymsTable)
      .where(eq(gymsTable.id, gymId))
      .get();

    if (!existingGym) {
      return NextResponse.json({ error: "Gym not found" }, { status: 404 });
    }

    // Soft delete - mark as inactive using Drizzle ORM
    await db
      .update(gymsTable)
      .set({ status: "inactive", updatedAt: new Date() })
      .where(eq(gymsTable.id, gymId));

    return NextResponse.json({
      success: true,
      message: "Gym deleted successfully",
    });
  } catch (error) {
    log.error("Failed to delete gym", error);
    return NextResponse.json(
      { error: "Internal Server Error" },
      { status: 500 },
    );
  }
}
