// @ts-nocheck
import { Request, Response } from 'express';
import asyncHandler from '../utils/asyncHandler';
import ApiError from '../utils/apiError';
import ApiResponse from '../utils/apiResponse';
import prisma from '../DB/db';

// --- Add New Address ---
export const addAddress = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.params?.id;
  const { street, city, state, zipCode, country, phone, type, isDefault, addressId,fullName,email } = req.body;

  // If setting as default, unset previous default
  if (isDefault) {
    await prisma.address.updateMany({
      where: { userId, isDefault: true },
      data: { isDefault: false },
    });
  }

  const address = await prisma.address.upsert({
    where: {
      id: addressId,
    },
    update: {
      email,
      fullName,
      street,
      city,
      state,
      zipCode,
      country,
      phone,
      type: type || 'HOME',
      isDefault: isDefault || false,
    },
    create: {
      userId: userId!,
      email,
      fullName,
      street,
      city,
      state,
      zipCode,
      country,
      phone,
      type: type || 'HOME',
      isDefault: isDefault || false,
    },
  });

  return res.status(201).json(new ApiResponse(true, 201, 'Address added', address));
});

// --- Get All Addresses ---
export const getAddresses = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.params?.id;

  const addresses = await prisma.address.findMany({
    where: { userId },
    orderBy: { isDefault: 'desc' }, // Default address comes first
  });

  return res.status(200).json(new ApiResponse(true, 200, 'Addresses fetched', addresses));
});

// --- Get Address  By Id ---
export const getAddressById = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;

  // Ensure user owns this address
  const address = await prisma.address.findFirst({
    where: { userId: id, isDefault: true },
  });

  return res.status(200).json(new ApiResponse(true, 200, 'Address Fetch Successfully',address));
});



// --- Delete Address ---
export const deleteAddress = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;
  const userId = req.user?.id;

  // Ensure user owns this address
  const address = await prisma.address.findFirst({
    where: { id, userId },
  });

  if (!address) throw new ApiError(false, 404, 'Address not found');

  await prisma.address.delete({ where: { id } });

  return res.status(200).json(new ApiResponse(true, 200, 'Address deleted'));
});
