import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, EntityManager } from 'typeorm';
import { SeekerCertification } from './entities/seeker_certification.entity';
import { CreateSeekerCertificationDto } from './dto/create-seeker_certification.dto';
import { UpdateSeekerCertificationDto } from './dto/update-seeker_certification.dto';

@Injectable()
export class SeekerCertificationsService {
  constructor(
    @InjectRepository(SeekerCertification)
    private seekerCertificationsRepository: Repository<SeekerCertification>,
    private readonly entityManager: EntityManager,
  ) {}

  private async getSeekerProfileId(userId: number): Promise<number> {
    const profile = await this.entityManager.query(
      'SELECT id FROM seeker_profiles WHERE user_id = ? LIMIT 1',
      [userId]
    );
    if (!profile || profile.length === 0) {
      throw new NotFoundException(`Seeker profile for user ${userId} not found`);
    }
    return profile[0].id;
  }

  async findAllBySeekerId(userId: number): Promise<SeekerCertification[]> {
    const seeker_id = await this.getSeekerProfileId(userId);
    return this.seekerCertificationsRepository.find({
      where: { seeker_id },
      order: { created_at: 'DESC' },
    });
  }

  async create(userId: number, createDto: CreateSeekerCertificationDto): Promise<SeekerCertification> {
    const seeker_id = await this.getSeekerProfileId(userId);
    const certification = this.seekerCertificationsRepository.create({
      ...createDto,
      seeker_id,
    });
    return this.seekerCertificationsRepository.save(certification);
  }

  async update(userId: number, id: number, updateDto: UpdateSeekerCertificationDto): Promise<SeekerCertification> {
    const seeker_id = await this.getSeekerProfileId(userId);
    const certification = await this.seekerCertificationsRepository.findOne({ where: { id, seeker_id } });
    
    if (!certification) {
      throw new NotFoundException(`SeekerCertification with ID ${id} not found`);
    }

    await this.seekerCertificationsRepository.update(id, updateDto);
    return this.seekerCertificationsRepository.findOne({ where: { id, seeker_id } });
  }

  async remove(userId: number, id: number): Promise<void> {
    const seeker_id = await this.getSeekerProfileId(userId);
    const certification = await this.seekerCertificationsRepository.findOne({ where: { id, seeker_id } });
    
    if (!certification) {
      throw new NotFoundException(`SeekerCertification with ID ${id} not found`);
    }

    await this.seekerCertificationsRepository.delete(id);
  }
}
