import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource } from 'typeorm';
import { JobsPostTag } from './entities/jobs_post_tag.entity';

@Injectable()
export class JobsPostTagService {
  constructor(
    @InjectRepository(JobsPostTag)
    private readonly jobsPostTagRepository: Repository<JobsPostTag>,
    private readonly dataSource: DataSource,
  ) {}

  // Create job-tag relationships
  async createJobTags(jobPostId: number, tagIds: number[]): Promise<void> {
    // Delete existing tags for this job
    await this.jobsPostTagRepository.delete({ job_post_id: jobPostId });

    // Insert new tags
    for (const tagId of tagIds) {
      const jobTag = this.jobsPostTagRepository.create({
        job_post_id: jobPostId,
        tag_id: tagId,
      });
      await this.jobsPostTagRepository.save(jobTag);
    }
  }

  // Get tags for a specific job
  async getTagsForJob(jobPostId: number): Promise<any[]> {
    return this.dataSource
      .createQueryBuilder()
      .select(['tag.id AS id', 'tag.name AS name'])
      .from('jobs_post_tag', 'jobTag')
      .leftJoin('tags', 'tag', 'tag.id = jobTag.tag_id')
      .where('jobTag.job_post_id = :jobPostId', { jobPostId })
      .getRawMany();
  }

  // Get all job-tag relationships
  async findAll(): Promise<JobsPostTag[]> {
    return this.jobsPostTagRepository.find();
  }

  // Delete all tags for a job
  async deleteJobTags(jobPostId: number): Promise<void> {
    await this.jobsPostTagRepository.delete({ job_post_id: jobPostId });
  }
}
