import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { JobPerks } from './entities/job_perks.entity';
import { Perks } from '../perks/entities/perks.entity';

@Injectable()
export class JobPerksService {
  constructor(
    @InjectRepository(JobPerks)
    private jobPerksRepository: Repository<JobPerks>,
    @InjectRepository(Perks)
    private perksRepository: Repository<Perks>,
  ) {}

  async findByJobId(jobId: number): Promise<any[]> {
    const jobPerks = await this.jobPerksRepository.find({
      where: { job_id: jobId },
      order: { created_at: 'ASC' },
    });

    // Get perk names for each job perk
    const perksWithNames = await Promise.all(
      jobPerks.map(async (jobPerk) => {
        if (jobPerk.perk_id) {
          const perk = await this.perksRepository.findOne({
            where: { id: jobPerk.perk_id },
          });
          return {
            ...jobPerk,
            perk_name: perk?.name || null,
          };
        }
        return jobPerk;
      }),
    );

    return perksWithNames;
  }

  async addPerkToJob(jobId: number, perkId: number): Promise<JobPerks> {
    // Check if perk already exists for this job
    const existingPerk = await this.jobPerksRepository.findOne({
      where: { job_id: jobId, perk_id: perkId },
    });

    if (existingPerk) {
      return existingPerk;
    }

    const jobPerk = this.jobPerksRepository.create({
      job_id: jobId,
      perk_id: perkId,
    });
    return this.jobPerksRepository.save(jobPerk);
  }

  async addCustomPerkToJob(
    jobId: number,
    customName: string,
  ): Promise<JobPerks> {
    const jobPerk = this.jobPerksRepository.create({
      job_id: jobId,
      custom_name: customName,
    });
    return this.jobPerksRepository.save(jobPerk);
  }

  async removePerkFromJob(jobId: number, perkId: number): Promise<void> {
    await this.jobPerksRepository.delete({
      job_id: jobId,
      perk_id: perkId,
    });
  }

  async removeCustomPerkFromJob(
    jobId: number,
    customName: string,
  ): Promise<void> {
    await this.jobPerksRepository.delete({
      job_id: jobId,
      custom_name: customName,
    });
  }

  async removeAllPerksFromJob(jobId: number): Promise<void> {
    await this.jobPerksRepository.delete({ job_id: jobId });
  }

  async updateJobPerks(
    jobId: number,
    perkIds: number[],
    customPerks: string[],
  ): Promise<void> {
    // Remove all existing perks for this job
    await this.removeAllPerksFromJob(jobId);

    // Add selected perks
    for (const perkId of perkIds) {
      await this.addPerkToJob(jobId, perkId);
    }

    // Add custom perks
    for (const customPerk of customPerks) {
      await this.addCustomPerkToJob(jobId, customPerk);
    }
  }
}
