import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";

const PreferencesSchema = z.object({
  theme: z.enum(["light", "dark", "system"]).optional(),
  defaultWeightUnit: z.enum(["lbs", "kg"]).optional(),
});

/**
 * GET /api/preferences
 * Get user preferences. Strips the dead Claude AI fields
 * (enableClaudeAI / claudeApiKey) — those columns still exist in the
 * schema but are slated for replacement by the model-agnostic AI work
 * (Option 3 / future). Don't reintroduce them in the response.
 */
export async function GET(_request: NextRequest) {
  try {
    const user = await getCurrentUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    let preferences = await prisma.userPreferences.findUnique({
      where: { userId: user.id },
    });

    if (!preferences) {
      preferences = await prisma.userPreferences.create({
        data: {
          userId: user.id,
          theme: "system",
          defaultWeightUnit: "lbs",
          defaultRestSeconds: 90,
        },
      });
    }

    const { claudeApiKey, enableClaudeAI, ...safe } = preferences;
    return NextResponse.json(safe);
  } catch (error) {
    console.error("GET /api/preferences error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}

/**
 * POST /api/preferences
 * Update user preferences. Only the fields in `PreferencesSchema` are
 * accepted; anything else (including the dead Claude AI fields) is
 * silently dropped at the Zod boundary.
 */
export async function POST(request: NextRequest) {
  try {
    const user = await getCurrentUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const validated = PreferencesSchema.parse(body);

    let preferences = await prisma.userPreferences.findUnique({
      where: { userId: user.id },
    });

    if (!preferences) {
      preferences = await prisma.userPreferences.create({
        data: {
          userId: user.id,
          ...validated,
        },
      });
    } else {
      preferences = await prisma.userPreferences.update({
        where: { userId: user.id },
        data: validated,
      });
    }

    const { claudeApiKey, enableClaudeAI, ...safe } = preferences;
    return NextResponse.json(safe);
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { error: "Validation error", details: error.errors },
        { status: 400 }
      );
    }
    console.error("POST /api/preferences error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
