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

@Injectable()
export class StateService {
  constructor(
    @InjectRepository(State)
    private readonly stateRepository: Repository<State>,
  ) {}

  // Fetch all records from state table
  async findAll() {
    return this.stateRepository
      .createQueryBuilder('s')
      .where('s.status = :status', { status: 1 })
      .orderBy('s.state_id', 'ASC')
      .getMany();
  }

  async findByCountry(
    countryId: number,
    page: number = 1,
    limit: number = 10,
    status?: number,
  ) {
    const skip = (page - 1) * limit;
    const where: any = { country_id: countryId };
    if (status !== undefined) where.status = status;

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

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

  async findOne(id: number): Promise<State> {
    return this.stateRepository.findOne({ where: { state_id: id } });
  }

  async create(createStateDto: any): Promise<any> {
    const newState = this.stateRepository.create(createStateDto);
    return this.stateRepository.save(newState);
  }

  async update(id: number, updateStateDto: any): Promise<any> {
    delete updateStateDto.id;
    await this.stateRepository.update({ state_id: id }, updateStateDto);
    return this.stateRepository.findOne({ where: { state_id: id } });
  }

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