import { NextRequest, NextResponse } from "next/server";
import db from "@/lib/db";
import { getLogger } from "@/utils/logger";
import { authOptions } from "@/app/api/auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";


const logger = getLogger("api/user/address/[addressuuid]");


export const DELETE = async (req: NextRequest, context: any) => {
  //!----------- Getting address-----------//
  const { params } = context;
  try {

    const session = await getServerSession(authOptions)

    if (!session) {
      return NextResponse.json({ mssg: "You are not authorized !" }, { status: 403 })
    }

    const userUuid = session.user.uuid 

    await db.address.delete({
      where: {
        uuid: params.addressuuid
      }
    })

    return NextResponse.json({mssg: "Address deleted successfully !"}, {status: 200})

  } catch (error: any) {
    logger.error("Error occurred when deleting user address", { errorMsg: error.message, errorData: error.config.data });
    return NextResponse.json({ error: "Internal server error !" }, { status: 500 })

  }
};

// export const POST = async (req: NextRequest, context: any) => {
//   //!----------- Getting address-----------//
//   const { params } = context;
//   const { address_line, post_code, city, district, division, updated_by } =
//     await req.json();
//   try {
//     // Check if the address already exists
//     // Check if the address already exists
//     const existingAddress = await db.address.findFirst({
//       where: {
//         address_line: address_line.trim(),
//         post_code: post_code.trim(),
//         city: city.trim(),
//         district: district.trim(),
//         division: division.trim(),
//         updated_by: updated_by,
//         profile: {
//           user: {
//             uuid: params.addressuuid,
//           },
//         },
//       },
//     });
//     if (existingAddress) {
//       return Response.json(
//         {
//           message: "Address already exists!",
//         },
//         { status: 400 }
//       );
//     }
//     // Find the user by UUID
//     const user = await db.user.findUnique({
//       where: {
//         uuid: params.addressuuid,
//       },
//     });

//     // Create a new address for the user if it doesn't exist
//     if (user) {
//       const newAddress = await db.address.create({
//         data: {
//           name: name.trim(),

//           address_line: address_line.trim(),
//           post_code: post_code.trim(),
//           city: city.trim(),
//           district: district.trim(),
//           division: division.trim(),
//           profile: {
//             connect: {
//               user_id: user.id,
//             },
//           },
//         },
//       });
//       return Response.json(
//         {
//           message: "New Address added!",
//         },
//         { status: 200 }
//       );
//     }
//   } catch (error) {
//     return Response.json(
//       {
//         message: error,
//       },
//       { status: 200 }
//     );
//   }
// };


export const PUT = async (req: NextRequest, context: any) => {

  const {params} = context

  try {
    const session = await getServerSession(authOptions)

    if (!session){
      return NextResponse.json({mssg: "You are not authorized !"}, {status: 403})
    }

    const data = await req.json()

    // console.log(data)

    // FIX IT

    const user = await db.user.findUnique({
      where: {
        uuid: session.user.uuid
      },
      include: {
        profile: true
      }
    })

    if (!user?.profile){
      return NextResponse.json({error: "User profile does not exist"}, {status: 403})
    }

    if (data.is_default){
      await db.address.updateMany({
        where: {
         profile_id: user.profile.id 
        },
        data: {
          is_default: false
        }
      })
    }

    const address = await db.address.update({
      where: {
        uuid: params.addressuuid
      },
      data: {
        name: data.name,
        phone: data.phone,
        is_default: data.is_default,
        address_line: data.address_line,
        post_code: data.post_code,
        city: data.city,
        district: data.district,
        division: data.division,
        shipping_zone_id: parseInt(data.shipping_zone),
        profile_id: user?.profile?.id 
        
      }
    })

    return NextResponse.json({mssg: address}, {status: 200})


  }
  catch(error:any){
    console.log(error)
    logger.error("Error occurred when updating user address", { errorMsg: error.message, errorData: error.config.data });
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}