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");

export const PUT = async (req: NextRequest, context: any) => {
  try {

    const session = await getServerSession(authOptions)

    if (!session) {
      return NextResponse.json({ mssg: "You are not authorized !" }, { status: 403 })
    }

    const { uuid, profileId } = await req.json();
    await db.address.updateMany({
      where: {
        profile_id: Number(profileId),
      },
      data: {
        is_default: false,
      },
    });

    /*    const updatetdAddress = await db.address.update({
          where: {
            uuid: uuid,
          },
          data: {
            is_default: true,
          },
        });*/

    return NextResponse.json({ message: "Updated Successfully " }, { status: 201 });
  } catch (error: any) {
    logger.error("Error occurred when updating user address", { errorMsg: error.message, errorData: error.config.data });
    return new NextResponse("Internal Server Error", { status: 500 });
  }
};

export const POST = async (req: NextRequest) => {
  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.create({
      data: {
        name: data.name,
        is_default: data.is_default,
        address_line: data.address_line,
        post_code: data.post_code,
        city: data.city,
        phone: data.phone,
        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 creating user address", { errorMsg: error.message, errorData: error.config.data });
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}


export const GET = async (req: NextRequest) => {
  try {
    const session = await getServerSession(authOptions);

    if (!session) {
      return NextResponse.json({ mssg: "You are not authorized !" }, { status: 403 })
    }

    const userUuid = session?.user.uuid

    const user = await db.user.findUnique({
      where: {
        uuid: userUuid
      },
      include: {
        profile: {
          include: {
            address: true
          }
        }
      }
    })


    // console.log(user?.profile?.address)

    if (user?.profile?.address) {

      return NextResponse.json({ mssg: user.profile.address }, { status: 200 })
    }

    else {
      return NextResponse.json({ mssg: "No user address found for this user" }, { status: 404 })
    }


  }
  catch (error: any) {
    logger.error("Error occured fetching the user address", { errorMsg: error.message, errorData: error.config.data })

    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}