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

@Injectable()
export class SocialPlatformService {
  constructor(
    @InjectRepository(SocialPlatform)
    private readonly socialPlatformRepository: Repository<SocialPlatform>,
  ) {}

  // Fetch all records from social_platform table
  async findAll() {
    return this.socialPlatformRepository
      .createQueryBuilder('sp')
      .orderBy('sp.id', 'ASC')
      .getMany();
  }

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

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

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

  async create(createSocialPlatformDto: any): Promise<any> {
    const newPlatform = this.socialPlatformRepository.create(
      createSocialPlatformDto,
    );
    return this.socialPlatformRepository.save(newPlatform);
  }

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

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