import { NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { eq, sql } from "@fitai/database";
import { db, users as usersTable } from "@fitai/database";
import { ensureUserSynced } from "@/lib/sync-user";
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 new NextResponse("Unauthorized", { status: 401 });
    }

    // Ensure user is synced
    const currentUser = await ensureUserSynced(userId, {
      getUserById: async (id: string) => {
        const row = await db
          .select()
          .from(usersTable)
          .where(eq(usersTable.id, id))
          .get();
        return row
          ? {
              id: row.id,
              email: row.email,
              firstName: row.firstName,
              lastName: row.lastName,
              password: row.password ?? "",
              phone: row.phone ?? undefined,
              role: row.role,
              imageUrl: undefined,
              createdAt: new Date(row.createdAt),
              updatedAt: new Date(row.updatedAt),
            }
          : null;
      },
    } as any);

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

    await ensureGymsTable();

    // Check if gym exists
    const gymRows = await db.all(sql`SELECT * FROM gyms WHERE id = ${gymId}`);
    if (gymRows.length === 0) {
      return new NextResponse("Gym not found", { status: 404 });
    }

    // Soft delete - mark as inactive
    await db.run(
      sql`UPDATE gyms SET status = 'inactive', updated_at = ${Date.now()} WHERE id = ${gymId}`,
    );

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