import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource } from 'typeorm';
import { SeekerExperience } from './entities/seeker_experience.entity';
import { SeekerProfiles } from '../seeker_profiles/entities/seeker_profiles.entity';

@Injectable()
export class SeekerExperienceService {
  constructor(
    @InjectRepository(SeekerExperience)
    private readonly seekerExperienceRepository: Repository<SeekerExperience>,
    private readonly dataSource: DataSource,
  ) {}

  async getProfileIdFromUserId(userId: number): Promise<number> {
    const profile = await this.dataSource.getRepository(SeekerProfiles).findOne({ where: { user_id: userId } });
    if (!profile) throw new NotFoundException('Seeker profile not found');
    return profile.id;
  }

  async create(userId: number, data: any) {
    const profileId = await this.getProfileIdFromUserId(userId);
    
    const exp = this.seekerExperienceRepository.create({
      seeker_id: profileId,
      designation: data.designation,
      department: data.department,
      company: data.company,
      employment_type_id: data.employment_type_id ? Number(data.employment_type_id) : null,
      start_date: data.start_date,
      end_date: data.current ? null : data.end_date,
      current: data.current ? true : false,
      responsibilities: data.responsibilities,
      skills: data.skills && Array.isArray(data.skills) ? data.skills : null,
      notice_period: data.current ? data.notice_period : null,
    });
    
    return await this.seekerExperienceRepository.save(exp);
  }

  async update(userId: number, id: number, data: any) {
    const profileId = await this.getProfileIdFromUserId(userId);
    
    const exp = await this.seekerExperienceRepository.findOne({ where: { id, seeker_id: profileId } });
    if (!exp) throw new NotFoundException('Experience not found or unauthorized');

    exp.designation = data.designation;
    exp.department = data.department;
    exp.company = data.company;
    exp.employment_type_id = data.employment_type_id ? Number(data.employment_type_id) : null;
    exp.start_date = data.start_date;
    exp.end_date = data.current ? null : data.end_date;
    exp.current = data.current ? true : false;
    exp.responsibilities = data.responsibilities;
    exp.skills = data.skills && Array.isArray(data.skills) ? data.skills : null;
    exp.notice_period = data.current ? data.notice_period : null;

    return await this.seekerExperienceRepository.save(exp);
  }

  async remove(userId: number, id: number) {
    const profileId = await this.getProfileIdFromUserId(userId);
    const exp = await this.seekerExperienceRepository.findOne({ where: { id, seeker_id: profileId } });
    if (!exp) throw new NotFoundException('Experience not found or unauthorized');

    await this.seekerExperienceRepository.remove(exp);
    return { success: true };
  }

  // Fetch all records from seeker_experience table
  async findAll() {
    return this.seekerExperienceRepository
      .createQueryBuilder('se')
      .orderBy('se.id', 'ASC')
      .getMany();
  }

  async findOne(id: number) {
    const exp = await this.seekerExperienceRepository.findOne({ where: { id } });
    if (!exp) throw new NotFoundException('Experience not found');
    return exp;
  }
}
