import { Injectable } from '@nestjs/common';
import { PrismaService } from '@modules/shared';
import { type IMacroDataService, type MacroDataPoint } from '../../domain/services/macro-data.service';

@Injectable()
export class PrismaMacroDataService implements IMacroDataService {
  constructor(private readonly prisma: PrismaService) {}

  async getByProvince(province: string, indicators?: string[]): Promise<MacroDataPoint[]> {
    const where: Record<string, unknown> = { province };
    if (indicators?.length) {
      where['indicator'] = { in: indicators };
    }

    const rows = await this.prisma.macroeconomicData.findMany({
      where,
      orderBy: [{ indicator: 'asc' }, { period: 'desc' }],
    });

    return rows.map((r) => ({
      province: r.province,
      indicator: r.indicator,
      value: r.value,
      unit: r.unit,
      period: r.period,
      source: r.source,
    }));
  }

  async getByIndicator(indicator: string, provinces?: string[]): Promise<MacroDataPoint[]> {
    const where: Record<string, unknown> = { indicator };
    if (provinces?.length) {
      where['province'] = { in: provinces };
    }

    const rows = await this.prisma.macroeconomicData.findMany({
      where,
      orderBy: [{ province: 'asc' }, { period: 'desc' }],
    });

    return rows.map((r) => ({
      province: r.province,
      indicator: r.indicator,
      value: r.value,
      unit: r.unit,
      period: r.period,
      source: r.source,
    }));
  }

  async upsert(data: MacroDataPoint): Promise<void> {
    await this.prisma.macroeconomicData.upsert({
      where: {
        province_indicator_period: {
          province: data.province,
          indicator: data.indicator,
          period: data.period,
        },
      },
      create: {
        province: data.province,
        indicator: data.indicator,
        value: data.value,
        unit: data.unit,
        period: data.period,
        source: data.source,
      },
      update: {
        value: data.value,
        unit: data.unit,
        source: data.source,
      },
    });
  }
}
