import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth";

/**
 * GET /api/clinic — return current clinic settings
 * PUT /api/clinic — update clinic settings (name, phone, timezone, quiet hours, etc.)
 *
 * Changes are immediately reflected everywhere:
 * - Chatbot reads clinic from DB on every message
 * - Reminders read clinic from DB on every send
 * - Dashboard reads clinic on every load
 */
export async function GET() {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const clinic = await prisma.clinic.findUnique({
    where: { id: session.id },
    select: {
      id: true,
      name: true,
      slug: true,
      email: true,
      phone: true,
      clinicType: true,
      timezone: true,
      quietHoursStart: true,
      quietHoursEnd: true,
      wahaStatus: true,
      wahaLastChecked: true,
      createdAt: true,
    },
  });

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

  return NextResponse.json(clinic);
}

export async function PUT(req: Request) {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  let body: Record<string, unknown>;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }

  // Only allow updating specific fields
  const VALID_CLINIC_TYPES = ["Medical Clinic","Dental Clinic","Beauty & Aesthetics","Physiotherapy","Mental Health","Pediatrics","Ophthalmology","Dermatology"];
  const allowed: Record<string, (v: unknown) => unknown> = {
    name: (v) => typeof v === "string" && v.trim().length > 0 ? v.toString().trim() : null,
    phone: (v) => typeof v === "string" ? v.toString().trim() : null,
    clinicType: (v) => typeof v === "string" && VALID_CLINIC_TYPES.includes(v) ? v : null,
    timezone: (v) => typeof v === "string" && v.trim().length > 0 ? v.toString().trim() : null,
    quietHoursStart: (v) => typeof v === "number" && v >= 0 && v <= 23 ? v : null,
    quietHoursEnd: (v) => typeof v === "number" && v >= 0 && v <= 23 ? v : null,
  };

  const updateData: Record<string, unknown> = {};

  for (const [key, validate] of Object.entries(allowed)) {
    if (body[key] !== undefined) {
      const validated = validate(body[key]);
      if (validated === null && body[key] !== null && body[key] !== "") {
        return NextResponse.json({ error: `Invalid value for ${key}` }, { status: 400 });
      }
      updateData[key] = validated ?? body[key];
    }
  }

  if (Object.keys(updateData).length === 0) {
    return NextResponse.json({ error: "No valid fields to update" }, { status: 400 });
  }

  // If name changed, also update slug
  if (updateData.name) {
    const newSlug = (updateData.name as string)
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/^-|-$/g, "");

    // Check slug isn't taken by another clinic
    const existing = await prisma.clinic.findFirst({
      where: { slug: newSlug, id: { not: session.id } },
    });
    if (!existing) {
      updateData.slug = newSlug;
    }
  }

  const clinic = await prisma.clinic.update({
    where: { id: session.id },
    data: updateData,
    select: {
      id: true,
      name: true,
      slug: true,
      email: true,
      phone: true,
      clinicType: true,
      timezone: true,
      quietHoursStart: true,
      quietHoursEnd: true,
      wahaStatus: true,
      createdAt: true,
    },
  });

  console.log(`✏️ Clinic updated: ${Object.keys(updateData).join(", ")}`);

  return NextResponse.json(clinic);
}
