import { ReportSnapshot as PrismaReportSnapshot } from '@prisma/client';
import { ReportSnapshot } from '../../../domain/aggregates/report-snapshot';
import {
  ReportType,
  ReportPeriod,
  SnapshotData,
  DataSource,
} from '../../../domain/value-objects';

export class ReportSnapshotMapper {
  static toDomain(raw: PrismaReportSnapshot): ReportSnapshot {
    const snapshotDataRaw = raw.snapshotData as {
      rows: any[];
      summary?: Record<string, any>;
      metadata?: Record<string, any>;
    };

    const snapshotData = SnapshotData.create({
      rows: snapshotDataRaw.rows || [],
      summary: snapshotDataRaw.summary,
      metadata: snapshotDataRaw.metadata,
    });

    const dataSource = DataSource.withFreshness(
      raw.dataSources,
      raw.dataFreshness,
    );

    return ReportSnapshot.reconstitute({
      id: raw.id,
      reportType: raw.reportType as ReportType,
      reportCode: raw.reportCode,
      reportPeriod: raw.reportPeriod as ReportPeriod,
      periodKey: raw.periodKey,
      snapshotData,
      dataSource,
      filterParams: raw.filterParams as Record<string, any> | null,
      periodStartAt: raw.periodStartAt,
      periodEndAt: raw.periodEndAt,
      generatedAt: raw.generatedAt,
      expiresAt: raw.expiresAt,
    });
  }

  static toPersistence(
    domain: ReportSnapshot,
  ): Omit<PrismaReportSnapshot, 'id'> & { id?: bigint } {
    return {
      id: domain.id || undefined,
      reportType: domain.reportType,
      reportCode: domain.reportCode,
      reportPeriod: domain.reportPeriod,
      periodKey: domain.periodKey,
      snapshotData: domain.snapshotData.toJSON(),
      summaryData: domain.snapshotData.summary,
      dataSources: domain.dataSource.sources,
      dataFreshness: domain.dataSource.dataFreshness,
      filterParams: domain.filterParams,
      rowCount: domain.rowCount,
      periodStartAt: domain.periodStartAt,
      periodEndAt: domain.periodEndAt,
      generatedAt: domain.generatedAt,
      expiresAt: domain.expiresAt,
    };
  }
}
