/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
  Count,
  CountSchema,
  Filter,
  FilterExcludingWhere,
  repository,
  Where,
} from '@loopback/repository';
import {
  del,
  get,
  getModelSchemaRef,
  param,
  patch,
  post,
  put,
  requestBody,
  response,
} from '@loopback/rest';
import {AddToCart, AddToCartRelations} from '../models';
import {AddToCartRepository} from '../repositories';

export class AddToCartController {
  constructor(
    @repository(AddToCartRepository)
    public addToCartRepository: AddToCartRepository,
  ) { }

  // Helper function to remove unwanted fields from add to cart
  private cleanAddToCart(addToCart: any): any {
    const {
      isDefault,
      isOn,
      isActive,
      createdDate,
      createdBy,
      modifiedDate,
      modifiedBy,
      deletedDate,
      deletedBy,
      deleteRemark,
      lastChanged,
      ...cleanedAddToCart
    } = addToCart;

    return cleanedAddToCart;
  }

  // Helper function to clean nested objects
  private cleanNestedObjects(addToCart: any): any {
    // Clean usertype if exists
    if (addToCart.usertype) {
      const {
        isDefault: userTypeIsDefault,
        isOn: userTypeIsOn,
        isActive: userTypeIsActive,
        createdDate: userTypeCreatedDate,
        createdBy: userTypeCreatedBy,
        modifiedDate: userTypeModifiedDate,
        modifiedBy: userTypeModifiedBy,
        deletedDate: userTypeDeletedDate,
        deletedBy: userTypeDeletedBy,
        deleteRemark: userTypeDeleteRemark,
        lastChanged: userTypeLastChanged,
        ...cleanedUsertype
      } = addToCart.usertype;

      addToCart.usertype = cleanedUsertype;
    }

    // Clean buyer if exists
    if (addToCart.buyer) {
      const {
        isDefault: buyerIsDefault,
        isOn: buyerIsOn,
        isActive: buyerIsActive,
        createdDate: buyerCreatedDate,
        createdBy: buyerCreatedBy,
        modifiedDate: buyerModifiedDate,
        modifiedBy: buyerModifiedBy,
        deletedDate: buyerDeletedDate,
        deletedBy: buyerDeletedBy,
        deleteRemark: buyerDeleteRemark,
        lastChanged: buyerLastChanged,
        ...cleanedBuyer
      } = addToCart.buyer;

      // Clean nested city if exists
      if (cleanedBuyer.city) {
        const {
          isDefault: cityIsDefault,
          isOn: cityIsOn,
          isActive: cityIsActive,
          createdDate: cityCreatedDate,
          createdBy: cityCreatedBy,
          modifiedDate: cityModifiedDate,
          modifiedBy: cityModifiedBy,
          deletedDate: cityDeletedDate,
          deletedBy: cityDeletedBy,
          deleteRemark: cityDeleteRemark,
          lastChanged: cityLastChanged,
          ...cleanedCity
        } = cleanedBuyer.city;

        cleanedBuyer.city = cleanedCity;
      }

      // Clean nested gender if exists
      if (cleanedBuyer.gender) {
        const {
          isDefault: genderIsDefault,
          isOn: genderIsOn,
          isActive: genderIsActive,
          createdDate: genderCreatedDate,
          createdBy: genderCreatedBy,
          modifiedDate: genderModifiedDate,
          modifiedBy: genderModifiedBy,
          deletedDate: genderDeletedDate,
          deletedBy: genderDeletedBy,
          deleteRemark: genderDeleteRemark,
          lastChanged: genderLastChanged,
          ...cleanedGender
        } = cleanedBuyer.gender;

        cleanedBuyer.gender = cleanedGender;
      }

      // Clean nested usertype if exists
      if (cleanedBuyer.usertype) {
        const {
          isDefault: buyerUserTypeIsDefault,
          isOn: buyerUserTypeIsOn,
          isActive: buyerUserTypeIsActive,
          createdDate: buyerUserTypeCreatedDate,
          createdBy: buyerUserTypeCreatedBy,
          modifiedDate: buyerUserTypeModifiedDate,
          modifiedBy: buyerUserTypeModifiedBy,
          deletedDate: buyerUserTypeDeletedDate,
          deletedBy: buyerUserTypeDeletedBy,
          deleteRemark: buyerUserTypeDeleteRemark,
          lastChanged: buyerUserTypeLastChanged,
          ...cleanedBuyerUsertype
        } = cleanedBuyer.usertype;

        cleanedBuyer.usertype = cleanedBuyerUsertype;
      }

      addToCart.buyer = cleanedBuyer;
    }

    // Clean seller if exists
    if (addToCart.seller) {
      const {
        isDefault: sellerIsDefault,
        isOn: sellerIsOn,
        isActive: sellerIsActive,
        createdDate: sellerCreatedDate,
        createdBy: sellerCreatedBy,
        modifiedDate: sellerModifiedDate,
        modifiedBy: sellerModifiedBy,
        deletedDate: sellerDeletedDate,
        deletedBy: sellerDeletedBy,
        deleteRemark: sellerDeleteRemark,
        lastChanged: sellerLastChanged,
        ...cleanedSeller
      } = addToCart.seller;

      // Clean nested city if exists
      if (cleanedSeller.city) {
        const {
          isDefault: cityIsDefault,
          isOn: cityIsOn,
          isActive: cityIsActive,
          createdDate: cityCreatedDate,
          createdBy: cityCreatedBy,
          modifiedDate: cityModifiedDate,
          modifiedBy: cityModifiedBy,
          deletedDate: cityDeletedDate,
          deletedBy: cityDeletedBy,
          deleteRemark: cityDeleteRemark,
          lastChanged: cityLastChanged,
          ...cleanedCity
        } = cleanedSeller.city;

        cleanedSeller.city = cleanedCity;
      }

      // Clean nested package if exists
      if (cleanedSeller.package) {
        const {
          isDefault: packageIsDefault,
          isOn: packageIsOn,
          isActive: packageIsActive,
          createdDate: packageCreatedDate,
          createdBy: packageCreatedBy,
          modifiedDate: packageModifiedDate,
          modifiedBy: packageModifiedBy,
          deletedDate: packageDeletedDate,
          deletedBy: packageDeletedBy,
          deleteRemark: packageDeleteRemark,
          lastChanged: packageLastChanged,
          ...cleanedPackage
        } = cleanedSeller.package;
        cleanedSeller.package = cleanedPackage;
      }

      // Clean nested user if exists
      if (cleanedSeller.user) {
        const {
          isDefault: userIsDefault,
          isOn: userIsOn,
          isActive: userIsActive,
          createdDate: userCreatedDate,
          createdBy: userCreatedBy,
          modifiedDate: userModifiedDate,
          modifiedBy: userModifiedBy,
          deletedDate: userDeletedDate,
          deletedBy: userDeletedBy,
          deleteRemark: userDeleteRemark,
          lastChanged: userLastChanged,
          ...cleanedUser
        } = cleanedSeller.user;

        cleanedSeller.user = cleanedUser;
      }

      // Clean nested gender if exists
      if (cleanedSeller.gender) {
        const {
          isDefault: genderIsDefault,
          isOn: genderIsOn,
          isActive: genderIsActive,
          createdDate: genderCreatedDate,
          createdBy: genderCreatedBy,
          modifiedDate: genderModifiedDate,
          modifiedBy: genderModifiedBy,
          deletedDate: genderDeletedDate,
          deletedBy: genderDeletedBy,
          deleteRemark: genderDeleteRemark,
          lastChanged: genderLastChanged,
          ...cleanedGender
        } = cleanedSeller.gender;

        cleanedSeller.gender = cleanedGender;
      }

      addToCart.seller = cleanedSeller;
    }

    // Clean postProperty if exists
    if (addToCart.postProperty) {
      const {
        isDefault: postPropertyIsDefault,
        isOn: postPropertyIsOn,
        isActive: postPropertyIsActive,
        createdDate: postPropertyCreatedDate,
        createdBy: postPropertyCreatedBy,
        modifiedDate: postPropertyModifiedDate,
        modifiedBy: postPropertyModifiedBy,
        deletedDate: postPropertyDeletedDate,
        deletedBy: postPropertyDeletedBy,
        deleteRemark: postPropertyDeleteRemark,
        lastChanged: postPropertyLastChanged,
        ...cleanedPostProperty
      } = addToCart.postProperty;

      addToCart.postProperty = cleanedPostProperty;
    }

    return addToCart;
  }

  @post('/add-to-carts')
  @response(200, {
    description: 'AddToCart model instance',
    content: {'application/json': {schema: getModelSchemaRef(AddToCart)}},
  })
  async create(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(AddToCart, {
            title: 'NewAddToCart',
            exclude: ['addTocartId'],
          }),
        },
      },
    })
    addToCart: Omit<AddToCart, 'addTocartId'>,
  ): Promise<AddToCart> {
    return this.addToCartRepository.create(addToCart);
  }

  @get('/add-to-carts/count')
  @response(200, {
    description: 'AddToCart model count',
    content: {'application/json': {schema: CountSchema}},
  })
  async count(
    @param.where(AddToCart) where?: Where<AddToCart>,
  ): Promise<Count> {
    return this.addToCartRepository.count(where);
  }

  // AddToCartController मध्ये
  @get('/add-to-carts')
  @response(200, {
    description: 'Array of AddToCart model instances with relations',
    content: {
      'application/json': {
        schema: {
          type: 'array',
          items: getModelSchemaRef(AddToCart, {includeRelations: true}),
        },
      },
    },
  })
  async find(
    @param.filter(AddToCart) filter?: Filter<AddToCart>,
  ): Promise<(AddToCart & AddToCartRelations)[]> {
    // Include usertype, buyer, seller, and postProperty relations
    const enhancedFilter = {
      ...filter,
      include: [
        {relation: 'usertype'},
        {relation: 'buyer'},
        {relation: 'seller'}, // ही ओळ जोडा
        {relation: 'postProperty'}
      ],
    };
    const addToCarts = await this.addToCartRepository.find(enhancedFilter);

    // Clean each add to cart
    const cleanedAddToCarts = addToCarts.map(addToCart => {
      let cleanedAddToCart = this.cleanAddToCart(addToCart);
      cleanedAddToCart = this.cleanNestedObjects(cleanedAddToCart);
      return cleanedAddToCart;
    });

    return cleanedAddToCarts;
  }

  @patch('/add-to-carts')
  @response(200, {
    description: 'AddToCart PATCH success count',
    content: {'application/json': {schema: CountSchema}},
  })
  async updateAll(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(AddToCart, {partial: true}),
        },
      },
    })
    addToCart: AddToCart,
    @param.where(AddToCart) where?: Where<AddToCart>,
  ): Promise<Count> {
    return this.addToCartRepository.updateAll(addToCart, where);
  }

  @get('/add-to-carts/{id}')
  @response(200, {
    description: 'AddToCart model instance with relations',
    content: {
      'application/json': {
        schema: getModelSchemaRef(AddToCart, {includeRelations: true}),
      },
    },
  })
  async findById(
    @param.path.number('id') id: number,
    @param.filter(AddToCart, {exclude: 'where'}) filter?: FilterExcludingWhere<AddToCart>
  ): Promise<AddToCart & AddToCartRelations> {
    // Include usertype, buyer, seller, and postProperty relations
    const enhancedFilter = {
      ...filter,
      include: [
        {relation: 'usertype'},
        {relation: 'buyer'},
        {relation: 'seller'},
        {relation: 'postProperty'}
      ],
    };
    const addToCart = await this.addToCartRepository.findById(id, enhancedFilter);

    // Clean the add to cart
    let cleanedAddToCart = this.cleanAddToCart(addToCart);
    cleanedAddToCart = this.cleanNestedObjects(cleanedAddToCart);

    return cleanedAddToCart;
  }

  @patch('/add-to-carts/{id}')
  @response(204, {
    description: 'AddToCart PATCH success',
  })
  async updateById(
    @param.path.number('id') id: number,
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(AddToCart, {partial: true}),
        },
      },
    })
    addToCart: AddToCart,
  ): Promise<void> {
    await this.addToCartRepository.updateById(id, addToCart);
  }

  @put('/add-to-carts/{id}')
  @response(204, {
    description: 'AddToCart PUT success',
  })
  async replaceById(
    @param.path.number('id') id: number,
    @requestBody() addToCart: AddToCart,
  ): Promise<void> {
    await this.addToCartRepository.replaceById(id, addToCart);
  }

  @del('/add-to-carts/{id}')
  @response(204, {
    description: 'AddToCart DELETE success',
  })
  async deleteById(@param.path.number('id') id: number): Promise<void> {
    await this.addToCartRepository.deleteById(id);
  }

  // Get cart items by buyer ID
  @get('/add-to-carts/buyer/{buyerId}')
  @response(200, {
    description: 'Array of AddToCart for a specific buyer',
    content: {
      'application/json': {
        schema: {
          type: 'array',
          items: getModelSchemaRef(AddToCart, {includeRelations: true}),
        },
      },
    },
  })
  async findByBuyer(
    @param.path.number('buyerId') buyerId: number,
  ): Promise<(AddToCart & AddToCartRelations)[]> {
    const addToCarts = await this.addToCartRepository.find({
      where: {
        fkBuyerIdSellerId: buyerId,
        fkUsertypeId: 1, // Buyer usertype
      },
      include: [
        {relation: 'usertype'},
        {relation: 'buyer'},
        {relation: 'postProperty'}
      ],
    });

    // Clean each add to cart
    return addToCarts.map(addToCart => {
      let cleanedAddToCart = this.cleanAddToCart(addToCart);
      cleanedAddToCart = this.cleanNestedObjects(cleanedAddToCart);
      return cleanedAddToCart;
    });
  }

  // Get cart items by seller ID
  @get('/add-to-carts/seller/{sellerId}')
  @response(200, {
    description: 'Array of AddToCart for a specific seller',
    content: {
      'application/json': {
        schema: {
          type: 'array',
          items: getModelSchemaRef(AddToCart, {includeRelations: true}),
        },
      },
    },
  })
  async findBySeller(
    @param.path.number('sellerId') sellerId: number,
  ): Promise<(AddToCart & AddToCartRelations)[]> {
    const addToCarts = await this.addToCartRepository.find({
      where: {
        fkBuyerIdSellerId: sellerId,
        fkUsertypeId: {neq: 1}, // Not buyer (seller or other)
      },
      include: [
        {relation: 'usertype'},
        {relation: 'seller'},
        {relation: 'postProperty'}
      ],
    });

    // Clean each add to cart
    return addToCarts.map(addToCart => {
      let cleanedAddToCart = this.cleanAddToCart(addToCart);
      cleanedAddToCart = this.cleanNestedObjects(cleanedAddToCart);
      return cleanedAddToCart;
    });
  }

  // Get cart count for logged-in user (buyer or seller)
  // Get cart count for logged-in user (buyer or seller)
  @get('/add-to-carts/user/{userId}/{userTypeId}/count')
  @response(200, {
    description: 'Cart item count for logged-in user',
    content: {
      'application/json': {schema: CountSchema},
    },
  })
  async getCartCountByUser(
    @param.path.number('userId') userId: number,
    @param.path.number('userTypeId') userTypeId: number, // MUST match path
  ): Promise<Count> {

    const whereCondition = {
      fkBuyerIdSellerId: userId,
      fkUsertypeId: userTypeId,
      isActive: 1,
    };

    console.log('Cart Count Where:', whereCondition); // 🔍 Debug log

    return this.addToCartRepository.count(whereCondition);
  }


}
