import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Experience } from './entities/experience.entity';

@Injectable()
export class ExperienceService {
  constructor(
    @InjectRepository(Experience)
    private readonly experienceRepository: Repository<Experience>,
  ) {}

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

  async findAllPaginated(page: number = 1, limit: number = 10) {
    const skip = (page - 1) * limit;
    const [data, total] = await this.experienceRepository.findAndCount({
      skip,
      take: limit,
      order: { level: 'ASC' },
    });

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

  async findOne(id: number): Promise<any> {
    return this.experienceRepository.findOne({ where: { id } });
  }

  async create(body: any): Promise<any> {
    const experience = this.experienceRepository.create(body);
    return this.experienceRepository.save(experience);
  }

  async update(id: number, body: any): Promise<any> {
    await this.experienceRepository.update(id, body);
    return this.findOne(id);
  }

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