import { ipcMain } from 'electron'

import { deleteReport, generateReports, loadReports, openReport } from '../services/reportService'
import type {
  DeleteReportResponse,
  GenerateReportsInput,
  GenerateReportsResponse,
  LoadReportsResponse,
  OpenReportResponse
} from '../types/report'

function getErrorMessage(error: unknown): string {
  return error instanceof Error ? error.message : '报告操作失败'
}

export function registerReportIpc(): void {
  ipcMain.handle('reports:load', async (): Promise<LoadReportsResponse> => {
    try {
      return {
        ok: true,
        reports: await loadReports()
      }
    } catch (error) {
      return {
        ok: false,
        message: getErrorMessage(error)
      }
    }
  })

  ipcMain.handle(
    'reports:generate',
    async (_, payload: GenerateReportsInput): Promise<GenerateReportsResponse> => {
      try {
        return {
          ok: true,
          ...(await generateReports(payload))
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

  ipcMain.handle('reports:open', async (_, filePath: string): Promise<OpenReportResponse> => {
    try {
      await openReport(filePath)
      return {
        ok: true
      }
    } catch (error) {
      return {
        ok: false,
        message: getErrorMessage(error)
      }
    }
  })

  ipcMain.handle('reports:delete', async (_, id: string): Promise<DeleteReportResponse> => {
    try {
      await deleteReport(id)
      return {
        ok: true
      }
    } catch (error) {
      return {
        ok: false,
        message: getErrorMessage(error)
      }
    }
  })
}
