import { ipcMain } from 'electron'

import {
  deleteTemplate,
  loadTemplates,
  openTemplate,
  parseTemplatePlaceholders,
  saveTemplate,
  selectTemplateFile
} from '../services/templateService'
import type {
  DeleteTemplateResponse,
  LoadTemplatesResponse,
  OpenTemplateResponse,
  ParseTemplatePlaceholdersResponse,
  SaveTemplateResponse,
  SelectTemplateFileResponse,
  TemplateInput
} from '../types/template'

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

export function registerTemplateIpc(): void {
  ipcMain.handle('templates:load', async (): Promise<LoadTemplatesResponse> => {
    try {
      return {
        ok: true,
        templates: await loadTemplates()
      }
    } catch (error) {
      return {
        ok: false,
        message: getErrorMessage(error)
      }
    }
  })

  ipcMain.handle('templates:select-file', async (): Promise<SelectTemplateFileResponse> => {
    try {
      const selectedFile = await selectTemplateFile()

      if (!selectedFile) {
        return {
          ok: false,
          canceled: true,
          message: '已取消选择'
        }
      }

      return {
        ok: true,
        ...selectedFile
      }
    } catch (error) {
      return {
        ok: false,
        message: getErrorMessage(error)
      }
    }
  })

  ipcMain.handle(
    'templates:parse-placeholders',
    async (_, filePath: string): Promise<ParseTemplatePlaceholdersResponse> => {
      try {
        return {
          ok: true,
          placeholders: await parseTemplatePlaceholders(filePath)
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

  ipcMain.handle(
    'templates:save',
    async (_, payload: TemplateInput): Promise<SaveTemplateResponse> => {
      try {
        return {
          ok: true,
          template: await saveTemplate(payload)
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

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

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