import { NextResponse } from "next/server";

import { getServerSession } from "next-auth";

import prismadb from "@/lib/prisma";

export async function POST(
  req: Request,
  { params }: { params: { storeId: string } }
) {
  try {
    const session = await getServerSession();
    const userId = session?.user?.email;

    const body = await req.json();

    const { name } = body;

    if (!userId) {
      return new NextResponse("Non authentifié", { status: 401 });
    }

    if (!name) {
      return new NextResponse("Nom requis", { status: 400 });
    }

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

    const storeByUserId = await prismadb.store.findFirst({
      where: {
        id: params.storeId,
      },
      include: {
        userToStore: {
          where: {
            userId: userId
          }
        }
      }
    });

    if (!storeByUserId) {
      return new NextResponse("Non autorisé", { status: 403 });
    }

    const brand = await prismadb.brand.create({
      data: {
        name,
        storeId: params.storeId
      }
    });

    return NextResponse.json(brand);

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

};

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

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

    const brands = await prismadb.brand.findMany({
      where: {
        storeId: params.storeId,
      },
    });

    return NextResponse.json(brands);

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

};