import { Injectable, NotFoundException } from '@nestjs/common';
import * as fs from 'fs';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, EntityManager } from 'typeorm';
import { SeekerEducation } from './entities/seeker_education.entity';
import { CreateSeekerEducationDto } from './dto/create-seeker_education.dto';
import { UpdateSeekerEducationDto } from './dto/update-seeker_education.dto';

@Injectable()
export class SeekerEducationService {
  constructor(
    @InjectRepository(SeekerEducation)
    private readonly seekerEducationRepository: Repository<SeekerEducation>,
    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 findAll() {
    return this.seekerEducationRepository
      .createQueryBuilder('se')
      .orderBy('se.id', 'ASC')
      .getMany();
  }

  async findByUserId(userId: number) {
    const seekerProfileId = await this.getSeekerProfileId(userId);
    return this.seekerEducationRepository.find({
      where: { seeker_id: seekerProfileId },
      order: { start_year: 'DESC', start_month: 'DESC', id: 'DESC' },
    });
  }

  async create(userId: number, createDto: CreateSeekerEducationDto) {
    try {
      const seekerProfileId = await this.getSeekerProfileId(userId);
      const newEdu = this.seekerEducationRepository.create({
        ...createDto,
        seeker_id: seekerProfileId,
      });
      return await this.seekerEducationRepository.save(newEdu);
    } catch (err) {
      fs.writeFileSync('backend_error.log', err.toString() + '\n' + err.stack);
      throw err;
    }
  }

  async update(userId: number, id: number, updateDto: UpdateSeekerEducationDto) {
    const seekerProfileId = await this.getSeekerProfileId(userId);
    const existing = await this.seekerEducationRepository.findOne({
      where: { id, seeker_id: seekerProfileId },
    });
    if (!existing) {
      throw new NotFoundException(`Education with ID ${id} not found`);
    }

    Object.assign(existing, updateDto);
    return this.seekerEducationRepository.save(existing);
  }

  async remove(userId: number, id: number) {
    const seekerProfileId = await this.getSeekerProfileId(userId);
    const existing = await this.seekerEducationRepository.findOne({
      where: { id, seeker_id: seekerProfileId },
    });
    if (!existing) {
      throw new NotFoundException(`Education with ID ${id} not found`);
    }

    await this.seekerEducationRepository.remove(existing);
    return { success: true };
  }
}
