import { BadRequestException, Injectable } from '@nestjs/common';
import { CreateTownDto } from './dto/create-town.dto';
import { Repository } from 'typeorm';
import { Town } from './entities/town.entity';
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
import { StateService } from 'src/state/state.service';
import { TownTraduction } from './entities/town-traduction.entity';
import { CreateTownTraductionDto } from './dto/create-town-trad.dto';
import { LANGUAGES } from 'src/enum/languages.enum';
import { DataSource } from 'typeorm';
import { ServerConstants } from 'src/constants/server.contants';
import { TownResDto } from './dto/town-res.dto';

@Injectable()
export class TownService {
  constructor(
    @InjectRepository(Town) private townRepository: Repository<Town>,
    @InjectRepository(TownTraduction) private townTradRepository: Repository<TownTraduction>,
    @InjectDataSource() private dataSource: DataSource,

    private state: StateService,
  ) {}

  async create(createTownDto: CreateTownDto) {
    const state = await this.state.findOne(createTownDto.state);
    if (!state) throw new BadRequestException('State does not exist');
    const town = await this.townRepository.save(createTownDto);
    const createTownTradDtoEN: CreateTownTraductionDto = {
      townId: town.townId,
      language: LANGUAGES.EN,
      name: createTownDto.name,
      description: createTownDto.descriptionEN,
    };

    const createTownTradDtoES: CreateTownTraductionDto = {
      townId: town.townId,
      language: LANGUAGES.ES,
      name: createTownDto.name,
      description: createTownDto.descriptionES,
    };

    await this.townTradRepository.save(createTownTradDtoES);
    await this.townTradRepository.save(createTownTradDtoEN);
  }

  async findTownsByState(stateId: number, lang: string): Promise<TownResDto[]> {
    const ans = await this.dataSource
      .getRepository(TownTraduction)
      .createQueryBuilder('townTrad')
      .leftJoin('townTrad.townId', 'town')
      .select([
        'town.townId AS townId',
        'town.name AS name',
        'town.imageName AS imageName',
        'townTrad.language AS language',
        'townTrad.description AS description',
        'town.state AS stateId',
      ])
      .where('town.state = :stateId', { stateId })
      .andWhere('townTrad.language = :language', { language: lang })
      .andWhere('town.active = true')
      .getRawMany();

    return ans.map((item: TownResDto) => ({
      townId: item.townId,
      name: item.name,
      imageName: `${ServerConstants.HOST}/towns/${item.imageName}`,
      description: item.description,
      stateId: item.stateId,
    }));
  }

  findAll() {
    return `This action returns all town`;
  }

  remove(id: number) {
    return `This action removes a #${id} town`;
  }
}
