/**
 * User Preferences API
 * GET - Fetch user preferences
 * PUT - Update user preferences
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { convexQuery, convexMutation } from "@/lib/convex-client";

/**
 * GET /api/user/preferences
 * Returns user preferences or creates default if not exists
 * Supports both NextAuth sessions and custom auth_token cookies (OTP login)
 */
export async function GET(request: NextRequest) {
  try {
    const userEmail = await getAuthenticatedEmail(request, auth);

    if (!userEmail) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    let prefs = (await convexQuery("auth/queries:getUserPreferences", {
      userId: user.id,
    })) as Record<string, unknown> | null;

    if (!prefs) {
      await convexMutation("auth/mutations:updatePreferences", {
        userId: user.id,
      });
      prefs = (await convexQuery("auth/queries:getUserPreferences", {
        userId: user.id,
      })) as Record<string, unknown> | null;
    }

    return NextResponse.json({
      success: true,
      preferences,
    });
  } catch (error) {
    console.error("[API] Failed to fetch preferences:", error);
    return NextResponse.json(
      { success: false, error: "Failed to fetch preferences" },
      { status: 500 },
    );
  }
}

/**
 * PUT /api/user/preferences
 * Updates user preferences
 * Rate limited to 30 requests per 15 minutes
 */
export async function PUT(request: NextRequest) {
  try {
    const userEmail = await getAuthenticatedEmail(request, auth);

    if (!userEmail) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    // Rate limiting
    const rateLimitResponse = await applyRateLimit(
      request,
      rateLimiters.authGeneral,
    );
    if (rateLimitResponse) return rateLimitResponse;

    // CSRF protection
    if (!validateCSRFToken(request)) {
      return NextResponse.json(
        { success: false, error: "Invalid CSRF token" },
        { status: 403 },
      );
    }

    const body = await request.json();
    const {
      language,
      timezone,
      dateFormat,
      emailNotifications,
      emailFrequency,
      dashboardPreferences,
    } = body;

    // Validate language
    if (language && !["ar", "en"].includes(language)) {
      return NextResponse.json(
        {
          success: false,
          error: 'Invalid language code. Must be "ar" or "en"',
        },
        { status: 400 },
      );
    }

    // Validate email frequency
    if (
      emailFrequency &&
      !["instant", "daily", "weekly"].includes(emailFrequency)
    ) {
      return NextResponse.json(
        { success: false, error: "Invalid email frequency" },
        { status: 400 },
      );
    }

    await convexMutation("auth/mutations:updatePreferences", {
      userId: user.id,
      language,
      timezone,
      dateFormat,
      emailNotifications,
      emailFrequency,
      dashboardPreferences,
    });

    const preferences = await convexQuery("auth/queries:getUserPreferences", {
      userId: user.id,
    });

    return NextResponse.json({
      success: true,
      preferences,
      message: "Preferences updated successfully",
    });
  } catch (error) {
    console.error("[API] Failed to update preferences:", error);
    return NextResponse.json(
      { success: false, error: "Failed to update preferences" },
      { status: 500 },
    );
  }
}
