import { NextResponse } from "next/server";
import { getAuthSession } from "@/core/auth";
import type { CompanyId } from "@/core/auth/types";
import {
  getPreference,
  savePreference,
  defaultPreference,
} from "@/core/notifications";
import type { NotificationType, NotificationPreference } from "@/core/notifications";

const VALID_TYPES: NotificationType[] = [
  "deadline-urgent",
  "deadline-overdue",
  "document-expiry",
  "status-change",
];

type SessionUser = {
  id?: string;
  name?: string | null;
  email?: string | null;
  company?: string;
};

/**
 * GET /api/notifications/preferences
 *
 * Returns the current user's notification preferences.
 * Creates defaults (all enabled) if none exist.
 */
export async function GET() {
  const session = await getAuthSession();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const u = session.user as SessionUser;
  const id = u.id ?? "unknown";
  const email = u.email ?? "";
  const name = u.name ?? "";
  const company = (u.company ?? "beletage") as CompanyId;

  let pref = await getPreference(id);

  if (!pref) {
    pref = defaultPreference(id, email, name, company);
    await savePreference(pref);
  }

  return NextResponse.json(pref);
}

/**
 * PUT /api/notifications/preferences
 *
 * Update the current user's notification preferences.
 * Body: { enabledTypes?: NotificationType[], globalOptOut?: boolean }
 */
export async function PUT(request: Request) {
  const session = await getAuthSession();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const u = session.user as SessionUser;
  const id = u.id ?? "unknown";
  const email = u.email ?? "";
  const name = u.name ?? "";
  const company = (u.company ?? "beletage") as CompanyId;

  const body = (await request.json()) as Partial<
    Pick<NotificationPreference, "enabledTypes" | "globalOptOut">
  >;

  // Validate types
  if (body.enabledTypes) {
    const invalid = body.enabledTypes.filter(
      (t) => !VALID_TYPES.includes(t),
    );
    if (invalid.length > 0) {
      return NextResponse.json(
        { error: `Tipuri invalide: ${invalid.join(", ")}` },
        { status: 400 },
      );
    }
  }

  // Load existing or create default
  let pref = await getPreference(id);
  if (!pref) {
    pref = defaultPreference(id, email, name, company);
  }

  // Update fields
  if (body.enabledTypes !== undefined) {
    pref.enabledTypes = body.enabledTypes;
  }
  if (body.globalOptOut !== undefined) {
    pref.globalOptOut = body.globalOptOut;
  }

  // Always refresh identity from session
  pref.email = email;
  pref.name = name;
  pref.company = company;

  await savePreference(pref);

  return NextResponse.json(pref);
}
