import { Injectable } from '@nestjs/common';
import { CreateStateDto } from './dto/create-state.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { State } from './entities/state.entity';
import { Repository } from 'typeorm';
import { ServerConstants } from 'src/constants/server.contants';
import { StateResponseDto } from './dto/state-res.dto';

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

  async create(createStateDto: CreateStateDto) {
    await this.stateRepository.save(createStateDto);
  }

  async findAll(): Promise<Array<StateResponseDto>> {
    const states = await this.stateRepository.find();
    const statesResponse: Array<StateResponseDto> = states.map(({ imageName, name, stateId }) => {
      return {
        stateId,
        name,
        imageURL: `${ServerConstants.HOST}/states/${imageName}`,
      };
    });

    return statesResponse;
  }

  async findOne(id: number) {
    const state = await this.stateRepository.findOneBy({ stateId: id });
    if (!state) return null;
    return {
      stateId: state.stateId,
      name: state.name,
      imageURL: `${ServerConstants.HOST}/states/${state.imageName}`,
    };
  }
}
