import { NextResponse } from "next/server";
import { createServerSupabaseClient } from "@/lib/supabase-server";
import { prisma } from "@/lib/prisma";

export async function GET() {
  try {
    const supabase = await createServerSupabaseClient();
    const { data: { user }, error: authError } = await supabase.auth.getUser();
    
    if (authError || !user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // 获取用户信息和订阅套餐
    const userWithPlan = await prisma.user.findUnique({
      where: { id: user.id },
      include: {
        subscriptionPlan: {
          include: {
            models: {
              where: { isActive: true },
              orderBy: [
                { provider: "asc" },
                { name: "asc" }
              ]
            }
          }
        }
      }
    });

    if (!userWithPlan) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }

    const models = userWithPlan.subscriptionPlan.models.map(model => ({
      id: model.id,
      modelId: model.modelId,
      name: model.name,
      provider: model.provider,
      serviceProvider: model.serviceProvider,
      outputType: model.outputType,
      description: model.description,
      maxTokens: model.maxTokens,
      inputCostPer1k: model.inputCostPer1k,
      outputCostPer1k: model.outputCostPer1k,
      supportedFeatures: model.supportedFeatures,
    }));

    return NextResponse.json({ models });
  } catch (error) {
    console.error("Error fetching available models:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}