import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SeekerAddress } from './entities/seeker_address.entity';

@Injectable()
export class SeekerAddressService {
  constructor(
    @InjectRepository(SeekerAddress)
    private readonly seekerAddressRepository: Repository<SeekerAddress>,
  ) {}

  // Fetch all records from seeker_address table
  async findAll() {
    return this.seekerAddressRepository
      .createQueryBuilder('sa')
      .orderBy('sa.id', 'ASC')
      .getMany();
  }

  /**
   * Centralized method to save/update seeker address with de-duplication
   */
  async upsertAddress(profileId: number, data: any) {
    if (!profileId) return { success: false, message: 'Profile ID required' };

    // Find all existing addresses for this profile
    const existingAddresses = await this.seekerAddressRepository.find({
      where: { seeker_profile_id: profileId },
      order: { id: 'ASC' },
    });

    // const isSameAsPermanent = data.sameAsPermanent ? 1 : 0;
    const rawSame = data.sameAsPermanent ?? data.same_as_permanent;
    const isSameAsPermanent =
      rawSame === true || rawSame === 'true' || rawSame === 1 || rawSame === '1'
        ? 1
        : 0;
    //   console.log('📍 [UPSERT_ADDRESS] sameAsPermanent debug:', {
    //       'data.sameAsPermanent': data.sameAsPermanent,
    //       'data.same_as_permanent': data.same_as_permanent,
    //       rawSame,
    //       typeofRawSame: typeof rawSame,
    //       isSameAsPermanent,
    //     });

    // Map data fields (handling both frontend camelCase and backend snake_case)
    const addressData: any = {
      seeker_profile_id: profileId,
      permanent_address:
        data.permanentAddress || data.permanent_address || data.currentAddress || null,
      permanent_pincode:
        data.permanentPincode || data.permanent_pincode || data.pincode || null,
      permanent_country_id:
        Number(data.permanentCountryId || data.permanent_country_id || data.country) || null,
      permanent_state_id:
        Number(data.permanentStateId || data.permanent_state_id || data.state) || null,
      permanent_city_id:
        Number(data.permanentCityId || data.permanent_city_id || data.city) || null,
      permanent_area_id:
        Number(data.permanentAreaId || data.permanent_area_id || data.area) || null,
      same_as_permanent: isSameAsPermanent,
    };

    // Handle communication address based on same_as_permanent
    if (isSameAsPermanent) {
      addressData.communication_address = addressData.permanent_address;
      addressData.communication_pincode = addressData.permanent_pincode;
      addressData.communication_country_id = addressData.permanent_country_id;
      addressData.communication_state_id = addressData.permanent_state_id;
      addressData.communication_city_id = addressData.permanent_city_id;
      addressData.communication_area_id = addressData.permanent_area_id;
    } else {
      addressData.communication_address =
        data.communicationAddress || data.communication_address || null;
      addressData.communication_pincode =
        data.communicationPincode || data.communication_pincode || null;
      addressData.communication_country_id =
        Number(data.communicationCountryId || data.communication_country_id) ||
        null;
      addressData.communication_state_id =
        Number(data.communicationStateId || data.communication_state_id) ||
        null;
      addressData.communication_city_id =
        Number(data.communicationCityId || data.communication_city_id) || null;
      addressData.communication_area_id =
        Number(data.communicationAreaId || data.communication_area_id) || null;
    }

    if (existingAddresses.length > 0) {
      // Update the first one
      const primaryAddress = existingAddresses[0];
      await this.seekerAddressRepository.update(primaryAddress.id, addressData);

      // Clean up any duplicates
      if (existingAddresses.length > 1) {
        const duplicateIds = existingAddresses.slice(1).map((a) => a.id);
        await this.seekerAddressRepository.delete(duplicateIds);
      }
      return { success: true, id: primaryAddress.id, action: 'updated' };
    } else {
      // Create new record
      const newAddress = await this.seekerAddressRepository.save(addressData);
      return { success: true, id: newAddress.id, action: 'created' };
    }
  }
}
