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

@Injectable()
export class PerksService {
  constructor(
    @InjectRepository(Perks)
    private perksRepository: Repository<Perks>,
  ) {}

  async findAll(): Promise<Perks[]> {
    return this.perksRepository.find({
      where: { status: 1 },
      order: { name: 'ASC' },
    });
  }

  async findAllPaginated(page: number = 1, limit: number = 10) {
    const skip = (page - 1) * limit;
    const [data, total] = await this.perksRepository.findAndCount({
      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<Perks> {
    return this.perksRepository.findOne({ where: { id } });
  }

  async create(createPerkDto: any): Promise<any> {
    const perk = this.perksRepository.create(createPerkDto);
    return this.perksRepository.save(perk);
  }

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

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