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(),
  enableClaudeAI: z.boolean().optional(),
  claudeApiKey: z.string().optional(),
});

/**
 * GET /api/preferences
 * Get user preferences
 */
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) {
      // Create default preferences
      preferences = await prisma.userPreferences.create({
        data: {
          userId: user.id,
          theme: "system",
          defaultWeightUnit: "lbs",
          defaultRestSeconds: 90,
          enableClaudeAI: false,
        },
      });
    }

    // Don't return API key in response
    const { claudeApiKey, ...safePreferences } = preferences;
    return NextResponse.json({
      ...safePreferences,
      claudeApiKey: claudeApiKey ? "***" : undefined,
    });
  } catch (error) {
    console.error("GET /api/preferences error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}

/**
 * POST /api/preferences
 * Update user preferences
 */
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);

    // Get or create preferences
    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,
      });
    }

    // Don't return API key in response
    const { claudeApiKey, ...safePreferences } = preferences;
    return NextResponse.json({
      ...safePreferences,
      claudeApiKey: claudeApiKey ? "***" : undefined,
    });
  } 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 }
    );
  }
}
