import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";

import prismadb from "@/lib/prisma";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, Authorization",
};

export async function OPTIONS() {
  return NextResponse.json({}, { headers: corsHeaders });
}

export async function GET(
  req: Request,
  { params }: { params: { storeId: string, amount: number } }
) {
  try {

    if (!params.storeId) {
      return new NextResponse("Boutique requise", { status: 400, headers: corsHeaders });
    }

    const paymentMethods = await prismadb.paymentMethodsToStore.findMany({
      where: {
        storeId: params.storeId,
        OR: [
          {
            active: true,
          },
          {
            testMode: true
          }
        ],
        AND: [
          {
            OR: [
              {
                AND: [
                  { minAmount: { lte: params.amount } },
                  { maxAmount: { gte: params.amount } }
                ]
              },
              {
                minAmount: { lte: params.amount },
                maxAmount: { equals: null }
              },
              {
                minAmount: { equals: null },
                maxAmount: { gte: params.amount }
              },
              {
                minAmount: { equals: null },
                maxAmount: { equals: null }
              }
            ]
          }
        ]
      },
      include: {
        paymentMethods: true
      },
      orderBy: {
        paymentMethodsId: 'desc'
      }
    });

    return NextResponse.json(paymentMethods, { headers: corsHeaders });

  } catch (error) {
    console.log('[PAYMENTMETHODS_GET]', error);
    return new NextResponse("Internal error", { status: 500, headers: corsHeaders })
  }

};