import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { S3Service } from '../aws/s3.service';
import { CacheKeys } from '../common/utils/cache-keys';
import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';

@Injectable()
export class MapsService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly redis: RedisService,
    private readonly s3: S3Service,
  ) {}

  async url(countryName: string, stateName: string) {
    const key = CacheKeys.mapUrl(countryName, stateName);
    const cached = await this.redis.getJson(key);
    if (cached) return { message: 'Map URL fetched successfully', data: cached };
    const map = await this.prisma.offlineMap.findFirst({
      where: {
        countryName: { equals: countryName, mode: 'insensitive' },
        stateName: { equals: stateName, mode: 'insensitive' },
        status: 'ACTIVE',
        uploadStatus: 'COMPLETED',
        deletedAt: null,
      },
      orderBy: { updatedAt: 'desc' },
    });
    if (!map || !map.s3Key) {
      throw new HttpException({
        message: 'No active completed map found for selected country and state',
        error: { code: 'MAP_NOT_FOUND' },
      }, HttpStatus.NOT_FOUND);
    }
    const data = {
      countryName: map.countryName,
      stateName: map.stateName,
      mapUrl: await this.s3.getDownloadUrl(map.s3Key),
      fileSize: Number(map.fileSize),
      updatedAt: map.updatedAt,
    };
    await this.redis.setJson(key, data, 900);
    return { message: 'Map URL fetched successfully', data };
  }
}
