"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateDataManagementService = generateDataManagementService;
function generateDataManagementService(context) {
    return /*ts*/ `
import { DispatcherService } from '@actions/dispatcher.service'
import type { DataModel, DataModelFlattened, ExcelDataModelFlattened } from '@decoders/data-model.decoder'
import {
  decodeDataModel,
  decodeExcelDataModel,
  flattenDataModel,
  flattenExcelDataModel,
} from '@decoders/data-model.decoder'
import type { Action_Import } from '@import/import.service'
import { forwardRef, Inject, Injectable, Logger } from '@nestjs/common'
import { DataService } from '@repositories/data.service'
import { XlPortService } from '@xlport/xlport.service'

import { timeStamp } from '@postxl/utils'

@Injectable()
export class DataManagementService {
  private readonly logger = new Logger(DataManagementService.name)

  constructor(
    private readonly dataService: DataService,
    private readonly xlPortService: XlPortService,
    @Inject(forwardRef(() => DispatcherService)) private readonly dispatcherService: DispatcherService,
  ) {}

  /**
   * Export raw Excel data to JSON
   * Uploads an Excel file and returns the cleaned tables as JSON
   */
  async exportRawExcel(fileBuffer: Buffer): Promise<{ filename: string; data: any }> {
    this.logger.log('Exporting raw Excel data to JSON')

    // Import from Excel
    const xlData = await this.xlPortService.importFromFile(fileBuffer)

    if (xlData.status !== 'success') {
      throw new Error(\`Error reading Excel file: \${xlData.message}\`)
    }

    // Clean the data
    const cleanedTables = this.xlPortService.replaceBlankStringsWithNull(
      this.xlPortService.replaceBlankTables(xlData.data.tables),
    )

    const filename = \`\${timeStamp()} raw-excel-export.json\`
    return { filename, data: cleanedTables }
  }

  /**
   * Export processed Excel data to JSON
   * Uploads an Excel file, decodes it, and returns the DataModel as JSON
   */
  async exportProcessedExcel(fileBuffer: Buffer): Promise<{ filename: string; data: DataModel }> {
    this.logger.log('Exporting processed Excel data to JSON')

    // Import and clean from Excel
    const xlData = await this.xlPortService.importFromFile(fileBuffer)

    if (xlData.status !== 'success') {
      throw new Error(\`Error reading Excel file: \${xlData.message}\`)
    }

    const cleanedTables = this.xlPortService.replaceBlankStringsWithNull(
      this.xlPortService.replaceBlankTables(xlData.data.tables),
    )

    // Decode to DataModel
    const dataModel = decodeExcelDataModel(cleanedTables as unknown as ExcelDataModelFlattened)

    const filename = \`\${timeStamp()} decoded-excel-export.json\`
    return { filename, data: dataModel }
  }

  /**
   * Export current database to JSON (Excel format)
   * Fetches all data from repositories and exports as ExcelDataModelFlattened
   */
  async exportDatabaseExcelFormat(): Promise<{ filename: string; data: ExcelDataModelFlattened }> {
    this.logger.log('Exporting database to Excel format JSON')

    // Fetch all data from repositories using the centralized method
    const dataModel = await this.dataService.${context.repositories.dataService.getAllAsDataModel}()

    // Flatten to Excel format
    const flattened = flattenExcelDataModel(dataModel)

    const filename = \`\${timeStamp()} database-excel-format-export.json\`
    return { filename, data: flattened }
  }

  /**
   * Export current database to JSON (JSON format)
   * Fetches all data from repositories and exports as DataModelFlattened
   */
  async exportDatabaseJsonFormat(): Promise<{ filename: string; data: DataModelFlattened }> {
    this.logger.log('Exporting database to JSON format')

    // Fetch all data from repositories using the centralized method
    const dataModel = await this.dataService.${context.repositories.dataService.getAllAsDataModel}()

    // Flatten to JSON format
    const flattened = flattenDataModel(dataModel)

    const filename = \`\${timeStamp()} database-json-format-export.json\`
    return { filename, data: flattened }
  }

  /**
   * Seed from raw Excel data
   * Clears database and imports data from Excel file
   */
  async seedFromRawExcel(fileBuffer: Buffer, originalFilename: string): Promise<{ success: boolean; result: any }> {
    this.logger.log('Seeding database from raw Excel data')

    // Clear database
    await this.dataService.init(true)

    // Dispatch import action
    const action: Action_Import = {
      scope: 'import',
      type: 'excelSeed',
      payload: {
        filename: originalFilename,
        data: fileBuffer,
      },
    }

    const result = await this.dispatcherService.dispatch({ action, user: this.dataService.users.rootUser })

    return { success: true, result }
  }

  /**
   * Seed from decoded JSON
   * Clears database and imports data from DataModel JSON
   */
  async seedFromDecodedJson(fileBuffer: Buffer): Promise<{ success: boolean; result: any }> {
    this.logger.log('Seeding database from decoded JSON')

    // Clear database
    await this.dataService.init(true)

    // Parse JSON to DataModel
    const data: DataModel = JSON.parse(fileBuffer.toString('utf-8'))

    // Dispatch import action
    const action: Action_Import = {
      scope: 'import',
      type: 'dataSeed',
      payload: data,
    }

    const result = await this.dispatcherService.dispatch({ action, user: this.dataService.users.rootUser })

    return { success: true, result }
  }

  /**
   * Seed from Excel-formatted JSON
   * Clears database and imports data from ExcelDataModelFlattened JSON
   */
  async seedFromExcelFormattedJson(fileBuffer: Buffer): Promise<{ success: boolean; result: any }> {
    this.logger.log('Seeding database from Excel-formatted JSON')

    // Clear database
    await this.dataService.init(true)

    // Parse and decode JSON
    const flatData: ExcelDataModelFlattened = JSON.parse(fileBuffer.toString('utf-8'))
    const data: DataModel = decodeExcelDataModel(flatData)

    // Dispatch import action
    const action: Action_Import = {
      scope: 'import',
      type: 'dataSeed',
      payload: data,
    }

    const result = await this.dispatcherService.dispatch({ action, user: this.dataService.users.rootUser })

    return { success: true, result }
  }

  /**
   * Seed from JSON-formatted JSON
   * Clears database and imports data from DataModelFlattened JSON
   */
  async seedFromJsonFormattedJson(fileBuffer: Buffer): Promise<{ success: boolean; result: any }> {
    this.logger.log('Seeding database from JSON-formatted JSON')

    // Clear database
    await this.dataService.init(true)

    // Parse and decode JSON
    const flatData: DataModelFlattened = JSON.parse(fileBuffer.toString('utf-8'))
    const data: DataModel = decodeDataModel(flatData)

    // Dispatch import action
    const action: Action_Import = {
      scope: 'import',
      type: 'dataSeed',
      payload: data,
    }

    const result = await this.dispatcherService.dispatch({ action, user: this.dataService.users.rootUser })

    return { success: true, result }
  }

  /**
   * Update from raw Excel data
   * Imports data from Excel file with delta detection
   */
  async updateFromRawExcel(
    fileBuffer: Buffer,
    originalFilename: string,
  ): Promise<{ success: boolean; result?: any; errors?: any }> {
    this.logger.log('Updating database from raw Excel data with delta detection')

    try {
      // Dispatch import action
      const action: Action_Import = {
        scope: 'import',
        type: 'excel',
        payload: {
          filename: originalFilename,
          data: fileBuffer,
        },
      }

      const result = await this.dispatcherService.dispatch({ action, user: this.dataService.users.rootUser })

      return { success: true, result }
    } catch (error) {
      this.logger.error('Error updating from raw Excel data', error)
      return { success: false, errors: error instanceof Error ? error.message : String(error) }
    }
  }

  /**
   * Update from decoded JSON
   * Imports data from DataModel JSON with delta detection
   */
  async updateFromDecodedJson(fileBuffer: Buffer): Promise<{ success: boolean; result?: any; errors?: any }> {
    this.logger.log('Updating database from decoded JSON with delta detection')

    // Parse JSON to DataModel
    const data: DataModel = JSON.parse(fileBuffer.toString('utf-8'))

    try {
      // Dispatch import action
      const action: Action_Import = {
        scope: 'import',
        type: 'data',
        payload: data,
      }

      const result = await this.dispatcherService.dispatch({ action, user: this.dataService.users.rootUser })

      return { success: true, result }
    } catch (error) {
      this.logger.error('Error updating from decoded JSON', error)
      return { success: false, errors: error instanceof Error ? error.message : String(error) }
    }
  }

  /**
   * Update from Excel-formatted JSON
   * Imports data from ExcelDataModelFlattened JSON with delta detection
   */
  async updateFromExcelFormattedJson(fileBuffer: Buffer): Promise<{ success: boolean; result?: any; errors?: any }> {
    this.logger.log('Updating database from Excel-formatted JSON with delta detection')

    try {
      // Parse and decode JSON
      const flatData: ExcelDataModelFlattened = JSON.parse(fileBuffer.toString('utf-8'))
      const data: DataModel = decodeExcelDataModel(flatData)

      // Dispatch import action
      const action: Action_Import = {
        scope: 'import',
        type: 'data',
        payload: data,
      }

      const result = await this.dispatcherService.dispatch({ action, user: this.dataService.users.rootUser })

      return { success: true, result }
    } catch (error) {
      this.logger.error('Error updating from Excel-formatted JSON', error)
      return { success: false, errors: error instanceof Error ? error.message : String(error) }
    }
  }

  /**
   * Update from JSON-formatted JSON
   * Imports data from DataModelFlattened JSON with delta detection
   */
  async updateFromJsonFormattedJson(fileBuffer: Buffer): Promise<{ success: boolean; result?: any; errors?: any }> {
    this.logger.log('Updating database from JSON-formatted JSON with delta detection')

    try {
      // Parse and decode JSON
      const flatData: DataModelFlattened = JSON.parse(fileBuffer.toString('utf-8'))
      const data: DataModel = decodeDataModel(flatData)

      // Dispatch import action
      const action: Action_Import = {
        scope: 'import',
        type: 'data',
        payload: data,
      }

      const result = await this.dispatcherService.dispatch({ action, user: this.dataService.users.rootUser })

      return { success: true, result }
    } catch (error) {
      this.logger.error('Error updating from JSON-formatted JSON', error)
      return { success: false, errors: error instanceof Error ? error.message : String(error) }
    }
  }
}
`;
}
//# sourceMappingURL=data-management-service.generator.js.map