import prismadb from "@/lib/prisma";
import { NextResponse } from "next/server";

import { getServerSession } from "next-auth";

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

    if (!params.brandId) {
      return new NextResponse("Id de marque requis", { status: 400 });
    }

    const brand = await prismadb.brand.findUnique({
      where: {
        id: params.brandId,
      }
    });

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

export async function PATCH(
  req: Request,
  { params }: { params: { storeId: string, brandId: 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.brandId) {
      return new NextResponse("Id de marque requis", { 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.updateMany({
      where: {
        id: params.brandId,
      },
      data: {
        name
      }
    });

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

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

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

    if (!params.brandId) {
      return new NextResponse("Id de marque requis", { 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.deleteMany({
      where: {
        id: params.brandId,
      }
    });

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