import { ipcMain } from 'electron'

import {
  addClassZodiacs,
  deleteClassWithProfiles,
  deleteStudentProfile,
  getStudentProfile,
  generateStudentComment,
  generateStudentComments,
  listStudentProfiles,
  loadStudentData,
  migrateStoredImagesToFiles,
  migrateLocalStudentData,
  pauseCommentGeneration,
  replaceProfilesForClass,
  resumeCommentGeneration,
  saveClasses,
  stopCommentGeneration,
  updateStudentProfile
} from '../services/studentService'
import type {
  AddClassZodiacsInput,
  AddClassZodiacsResponse,
  ClassProfile,
  ChildProfile,
  DeleteClassResponse,
  DeleteStudentProfileResponse,
  GenerateStudentCommentInput,
  GenerateStudentCommentResponse,
  GenerateStudentCommentsInput,
  GenerateStudentCommentsResponse,
  GetStudentProfileResponse,
  LoadStudentDataInput,
  ListStudentProfilesInput,
  ListStudentProfilesResponse,
  LoadStudentDataResponse,
  ReplaceClassProfilesResponse,
  SaveClassesResponse,
  TaskControlResponse,
  UpdateStudentProfileInput,
  UpdateStudentProfileResponse
} from '../types/student'

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

export function registerStudentIpc(): void {
  void migrateStoredImagesToFiles().catch((error) => {
    console.error('[图片迁移] 迁移 SQLite 内图片到文件失败', error)
  })

  ipcMain.handle(
    'student:load',
    async (_, payload?: LoadStudentDataInput): Promise<LoadStudentDataResponse> => {
      try {
        const studentData = await loadStudentData(payload)
        return {
          ok: true,
          ...studentData
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

  ipcMain.handle(
    'student:list',
    async (_, payload: ListStudentProfilesInput): Promise<ListStudentProfilesResponse> => {
      try {
        return {
          ok: true,
          ...(await listStudentProfiles(payload))
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

  ipcMain.handle(
    'student:get-profile',
    async (_, profileId: string): Promise<GetStudentProfileResponse> => {
      try {
        return {
          ok: true,
          profile: await getStudentProfile(profileId)
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

  ipcMain.handle(
    'student:update-profile',
    async (_, payload: UpdateStudentProfileInput): Promise<UpdateStudentProfileResponse> => {
      try {
        return {
          ok: true,
          profile: await updateStudentProfile(payload)
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

  ipcMain.handle(
    'student:generate-comment',
    async (_, payload: GenerateStudentCommentInput): Promise<GenerateStudentCommentResponse> => {
      try {
        return {
          ok: true,
          profile: await generateStudentComment(payload.profileId)
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

  ipcMain.handle(
    'student:generate-comments',
    async (_, payload: GenerateStudentCommentsInput): Promise<GenerateStudentCommentsResponse> => {
      try {
        return {
          ok: true,
          ...(await generateStudentComments(payload))
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

  ipcMain.handle(
    'student:add-class-zodiacs',
    async (_, payload: AddClassZodiacsInput): Promise<AddClassZodiacsResponse> => {
      try {
        return {
          ok: true,
          ...(await addClassZodiacs(payload.classId))
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

  ipcMain.handle(
    'comments:pause-generation',
    async (_, batchId: string): Promise<TaskControlResponse> => {
      if (pauseCommentGeneration(batchId)) {
        return { ok: true }
      }

      return {
        ok: false,
        message: '当前没有可暂停的评语生成任务'
      }
    }
  )

  ipcMain.handle(
    'comments:resume-generation',
    async (_, batchId: string): Promise<TaskControlResponse> => {
      if (resumeCommentGeneration(batchId)) {
        return { ok: true }
      }

      return {
        ok: false,
        message: '当前没有可继续的评语生成任务'
      }
    }
  )

  ipcMain.handle(
    'comments:stop-generation',
    async (_, batchId: string): Promise<TaskControlResponse> => {
      if (stopCommentGeneration(batchId)) {
        return { ok: true }
      }

      return {
        ok: false,
        message: '当前没有可停止的评语生成任务'
      }
    }
  )

  ipcMain.handle(
    'student:save-classes',
    async (_, classes: ClassProfile[]): Promise<SaveClassesResponse> => {
      try {
        await saveClasses(classes)
        return {
          ok: true
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

  ipcMain.handle(
    'student:replace-class-profiles',
    async (
      _,
      payload: { classItem: ClassProfile; profiles: ChildProfile[] }
    ): Promise<ReplaceClassProfilesResponse> => {
      try {
        return {
          ok: true,
          ...(await replaceProfilesForClass(payload.classItem, payload.profiles))
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

  ipcMain.handle(
    'student:delete-class',
    async (_, classId: string): Promise<DeleteClassResponse> => {
      try {
        await deleteClassWithProfiles(classId)
        return {
          ok: true
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

  ipcMain.handle(
    'student:delete-profile',
    async (_, profileId: string): Promise<DeleteStudentProfileResponse> => {
      try {
        await deleteStudentProfile(profileId)
        return {
          ok: true
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )

  ipcMain.handle(
    'student:migrate-local',
    async (
      _,
      payload: { classes: ClassProfile[]; profiles: ChildProfile[] }
    ): Promise<SaveClassesResponse> => {
      try {
        await migrateLocalStudentData(payload.classes, payload.profiles)
        return {
          ok: true
        }
      } catch (error) {
        return {
          ok: false,
          message: getErrorMessage(error)
        }
      }
    }
  )
}
