import { ReportDefinition as PrismaReportDefinition } from '@prisma/client';
import { ReportDefinition } from '../../../domain/aggregates/report-definition';
import { ReportType, ReportSchedule, OutputFormat } from '../../../domain/value-objects';

export class ReportDefinitionMapper {
  static toDomain(raw: PrismaReportDefinition): ReportDefinition {
    const schedule =
      raw.scheduleCron
        ? ReportSchedule.create(
            raw.scheduleCron,
            raw.scheduleTimezone || 'Asia/Shanghai',
            raw.scheduleEnabled,
          )
        : null;

    return ReportDefinition.reconstitute({
      id: raw.id,
      reportType: raw.reportType as ReportType,
      reportName: raw.reportName,
      reportCode: raw.reportCode,
      description: raw.description || '',
      parameters: raw.parameters as Record<string, any>,
      schedule,
      outputFormats: raw.outputFormats as OutputFormat[],
      isActive: raw.isActive,
      createdAt: raw.createdAt,
      lastGeneratedAt: raw.lastGeneratedAt,
    });
  }

  static toPersistence(domain: ReportDefinition): Omit<PrismaReportDefinition, 'id' | 'updatedAt'> & { id?: bigint } {
    return {
      id: domain.id || undefined,
      reportType: domain.reportType,
      reportName: domain.reportName,
      reportCode: domain.reportCode,
      description: domain.description,
      parameters: domain.parameters,
      scheduleCron: domain.schedule?.cronExpression || null,
      scheduleTimezone: domain.schedule?.timezone || 'Asia/Shanghai',
      scheduleEnabled: domain.schedule?.enabled || false,
      outputFormats: domain.outputFormats,
      isActive: domain.isActive,
      createdAt: domain.createdAt,
      lastGeneratedAt: domain.lastGeneratedAt,
    };
  }
}
