import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { UMMAHID_URL } from "@/lib/auth";
import { checkRateLimit, getClientIp } from "@/lib/rate-limit";

export async function POST(req: NextRequest) {
  try {
    const ip = getClientIp(req);
    const { allowed } = checkRateLimit(ip);
    if (!allowed) {
      return NextResponse.json(
        { error: "Too many requests. Try again later." },
        { status: 429, headers: { "Retry-After": "900", "X-RateLimit-Remaining": "0" } }
      );
    }

    const { email, password } = await req.json();

    if (!email || !password) {
      return NextResponse.json(
        { error: "Email and password are required" },
        { status: 400 }
      );
    }

    // Proxy to Ummah ID
    const ummahRes = await fetch(`${UMMAHID_URL}/api/auth/login`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, password }),
    });

    const ummahData = await ummahRes.json();

    if (!ummahRes.ok) {
      return NextResponse.json(
        { error: ummahData.error || "Authentication failed" },
        { status: ummahRes.status }
      );
    }

    const { token, user: ummahUser } = ummahData;

    // Find or create local user by email
    let localUser = await prisma.user.findUnique({ where: { email } });
    if (!localUser) {
      localUser = await prisma.user.create({
        data: {
          email,
          name: ummahUser?.name || email?.split("@")[0] || "User",
          provider: "ummahid",
          providerId: ummahUser.id,
          flhBalance: 5000,
        },
      });
    }

    return NextResponse.json({
      token,
      user: {
        id: localUser.id,
        email: localUser.email,
        name: localUser.name,
        isPremium: localUser.isPremium,
        isPro: localUser.isPro,
        flhBalance: localUser.flhBalance,
        dailyMsgCount: localUser.dailyMsgCount,
      },
    });
  } catch (error) {
    console.error("Login error:", error);
    return NextResponse.json(
      { error: "Login failed. Please try again." },
      { status: 500 }
    );
  }
}
