import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, EntityManager } from 'typeorm';
import { SeekerResume } from './entities/seeker_resumes.entity';
import * as fs from 'fs';
import { promisify } from 'util';
const unlinkAsync = promisify(fs.unlink);

@Injectable()
export class SeekerResumesService {
  constructor(
    @InjectRepository(SeekerResume)
    private seekerResumesRepository: Repository<SeekerResume>,
    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 getResumes(userId: number) {
    const seekerProfileId = await this.getSeekerProfileId(userId);
    return this.seekerResumesRepository.find({
      where: { seeker_id: seekerProfileId, is_deleted: false },
      order: { uploaded_at: 'DESC' },
    });
  }

  async uploadResume(userId: number, file: Express.Multer.File) {
    const seekerProfileId = await this.getSeekerProfileId(userId);

    // Check limit
    const count = await this.seekerResumesRepository.count({
      where: { seeker_id: seekerProfileId, is_deleted: false },
    });

    if (count >= 5) {
      // Delete uploaded file since we reject it
      if (file.path && fs.existsSync(file.path)) {
        await unlinkAsync(file.path);
      }
      throw new BadRequestException('You can only upload a maximum of 5 resumes.');
    }

    const resume = this.seekerResumesRepository.create({
      seeker_id: seekerProfileId,
      file_url: file.path,
      file_name: file.originalname,
      name: file.originalname,
      uploaded_at: new Date(),
      is_deleted: false,
    });
    console.log('UPLOADED FILE IN SERVICE:', file);
    console.log('RESUME ENTITY BEFORE SAVE:', resume);
    
    await this.seekerResumesRepository.save(resume);
    return { success: true, resume_id: resume.id, file_url: file.path };
  }

  async deleteResume(userId: number, id: number) {
    const seekerProfileId = await this.getSeekerProfileId(userId);
    const resume = await this.seekerResumesRepository.findOne({
      where: { id, seeker_id: seekerProfileId, is_deleted: false },
    });

    if (!resume) {
      throw new NotFoundException('Resume not found');
    }

    resume.is_deleted = true;
    await this.seekerResumesRepository.save(resume);
    return { success: true, message: 'Resume deleted successfully' };
  }

  async replaceResume(userId: number, id: number, file: Express.Multer.File) {
    const seekerProfileId = await this.getSeekerProfileId(userId);
    const resume = await this.seekerResumesRepository.findOne({
      where: { id, seeker_id: seekerProfileId, is_deleted: false },
    });

    if (!resume) {
      // Delete uploaded file since we reject it
      if (file.path && fs.existsSync(file.path)) {
        await unlinkAsync(file.path);
      }
      throw new NotFoundException('Resume not found');
    }

    // Optional: soft delete the old file logic isn't needed for the physical file if we want to keep it, but normally we might remove it to save space. We will keep it on disk for soft-deleted records.
    resume.file_url = file.path;
    resume.file_name = file.originalname;
    resume.name = file.originalname;
    resume.uploaded_at = new Date();
    
    await this.seekerResumesRepository.save(resume);
    return { success: true, resume_id: resume.id, file_url: file.path };
  }
}
