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

@Injectable()
export class RoleLevelsService {
  constructor(
    @InjectRepository(RoleLevels)
    private readonly roleLevelsRepository: Repository<RoleLevels>,
    private readonly dataSource: DataSource,
  ) {}

  async findAll(): Promise<RoleLevels[]> {
    return this.roleLevelsRepository.find({ where: { status: 1 } });
  }

  async findAllPaginated(
    page: number = 1,
    limit: number = 10,
    industryId?: number,
  ) {
    const skip = (page - 1) * limit;
    const where: any = {};
    if (industryId) {
      where.industryId = industryId;
    }

    const [data, total] = await this.roleLevelsRepository.findAndCount({
      where,
      skip,
      take: limit,
      order: { name: 'ASC' },
    });

    return {
      success: true,
      data,
      meta: {
        totalItems: total,
        itemsPerPage: limit,
        currentPage: page,
        totalPages: Math.ceil(total / limit),
      },
    };
  }

  async findOne(id: number): Promise<RoleLevels | null> {
    return this.roleLevelsRepository.findOne({ where: { id } });
  }

  async create(body: any): Promise<RoleLevels> {
    const { industry_id, ...rest } = body;
    const roleLevel = this.roleLevelsRepository.create({
      ...rest,
      industryId: industry_id,
    }) as unknown as RoleLevels;
    return this.roleLevelsRepository.save(roleLevel);
  }

  async update(id: number, body: any): Promise<RoleLevels | null> {
    const { industry_id, ...rest } = body;
    const updateData: any = { ...rest };
    if (industry_id !== undefined) {
      updateData.industryId = industry_id;
    }
    await this.roleLevelsRepository.update(id, updateData);
    return this.findOne(id);
  }

  async remove(id: number): Promise<void> {
    await this.roleLevelsRepository.delete(id);
  }

  async getRoleLevelsWithCounts() {
    return (
      this.dataSource
        .createQueryBuilder()
        .select([
          'rl.id as id',
          'rl.name as name',
          'COUNT(DISTINCT jp.id) as job_count',
        ])
        .from('role_levels', 'rl')
        .leftJoin('roles', 'r', 'r.role_levels_id = rl.id')
        .leftJoin(
          'job_posts',
          'jp',
          '(jp.role_levels_id = rl.id OR (jp.role_levels_id IS NULL AND jp.role_id = r.id)) AND jp.status = :status AND (jp.expires_at IS NULL OR jp.expires_at > NOW())',
          { status: 'open' },
        )
        .leftJoin('companies', 'co', 'co.id = jp.company_id')
        .where('rl.status = :activeStatus', { activeStatus: 1 })
        // Ensure we only count jobs from active/non-deleted companies
        .andWhere('(jp.id IS NULL OR (co.status = 1 AND co.is_deleted = 0))')
        .groupBy('rl.id, rl.name')
        .orderBy('job_count', 'DESC')
        .getRawMany()
    );
  }
}
