"use server"

import { revalidatePath } from "next/cache"
import { z } from "zod"

import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import type { ActionState } from "@/shared/types/action-state"
import { parseExcel } from "@/shared/lib/excel"
import { formatDateForFile } from "@/shared/lib/utils"

import {
  batchImportUsers,
  exportUsersToExcel,
  generateUserImportTemplate,
  parseUserImportData,
  type UserImportResult,
} from "./import-export"
import { deleteUserById, updateUserProfileById, type UpdateUserProfileInput } from "./data-access"

/** Zod schema for self-service profile update (P0-13) */
const UpdateUserProfileSchema = z.object({
  name: z.string().min(1).max(100).optional(),
  phone: z.string().max(30).optional(),
  address: z.string().max(200).optional(),
  gender: z.string().max(20).optional(),
  age: z.number().int().min(0).max(150).optional(),
})

export type { UpdateUserProfileInput }

/**
 * Self-service profile update (P0-13 修复)
 *
 * - Uses requirePermission(USER_PROFILE_UPDATE) instead of requireAuth()
 * - DB operation delegated to data-access.updateUserProfileById
 * - Returns ActionState<void> instead of Promise<void>
 * - Input validated by Zod schema
 */
export async function updateUserProfile(
  data: UpdateUserProfileInput
): Promise<ActionState<void>> {
  try {
    const ctx = await requirePermission(Permissions.USER_PROFILE_UPDATE)

    const parsed = UpdateUserProfileSchema.safeParse(data)
    if (!parsed.success) {
      return {
        success: false,
        message: "Validation failed",
        errors: parsed.error.flatten().fieldErrors,
      }
    }

    await updateUserProfileById(ctx.userId, parsed.data)

    revalidatePath("/profile")
    revalidatePath("/settings")

    return { success: true, message: "Profile updated successfully" }
  } catch (e) {
    if (e instanceof PermissionDeniedError) {
      return { success: false, message: e.message }
    }
    if (e instanceof Error) {
      return { success: false, message: e.message }
    }
    return { success: false, message: "Failed to update profile" }
  }
}

/**
 * 生成用户导入模板（返回 base64 编码的 Excel）
 */
export async function downloadUserTemplateAction(): Promise<ActionState<string>> {
  try {
    await requirePermission(Permissions.USER_MANAGE)
    const buffer = await generateUserImportTemplate()
    return {
      success: true,
      data: buffer.toString("base64"),
      message: "user_import_template.xlsx",
    }
  } catch (e) {
    if (e instanceof PermissionDeniedError) {
      return { success: false, message: e.message }
    }
    return { success: false, message: "Failed to generate template" }
  }
}

/**
 * 导入用户：接收文件，解析+验证+导入
 */
export async function importUsersAction(
  prevState: ActionState<UserImportResult> | null,
  formData: FormData
): Promise<ActionState<UserImportResult>> {
  try {
    await requirePermission(Permissions.USER_MANAGE)

    const file = formData.get("file")
    if (!(file instanceof File)) {
      return { success: false, message: "请选择文件" }
    }

    const lowerName = file.name.toLowerCase()
    if (!lowerName.endsWith(".xlsx") && !lowerName.endsWith(".xls")) {
      return { success: false, message: "仅支持 .xlsx 和 .xls 文件" }
    }

    const bytes = Buffer.from(await file.arrayBuffer())
    const sheets = await parseExcel(bytes)
    if (sheets.length === 0) {
      return { success: false, message: "文件中无数据" }
    }

    const validation = parseUserImportData(sheets[0].rows)
    if (validation.invalid.length > 0 && validation.valid.length === 0) {
      return {
        success: false,
        message: `所有 ${validation.invalid.length} 行数据均无效`,
        errors: {
          invalid: validation.invalid.map((r) => `第 ${r.row} 行: ${r.errors.join("; ")}`),
        },
      }
    }

    const result = await batchImportUsers(validation.valid)
    revalidatePath("/admin/users/import")

    return {
      success: true,
      message: `成功导入 ${result.successCount} 个用户，失败 ${result.failedCount} 个`,
      data: result,
    }
  } catch (e) {
    if (e instanceof PermissionDeniedError) {
      return { success: false, message: e.message }
    }
    if (e instanceof Error) return { success: false, message: e.message }
    return { success: false, message: "导入失败" }
  }
}

/**
 * 导出用户列表（返回 base64 编码的 Excel）
 */
export async function exportUsersAction(
  role?: string
): Promise<ActionState<{ buffer: string; filename: string }>> {
  try {
    const ctx = await requirePermission(Permissions.USER_MANAGE)
    const buffer = await exportUsersToExcel({ scope: ctx.dataScope, role })
    return {
      success: true,
      data: {
        buffer: buffer.toString("base64"),
        filename: `users_export_${formatDateForFile()}.xlsx`,
      },
    }
  } catch (e) {
    if (e instanceof PermissionDeniedError) {
      return { success: false, message: e.message }
    }
    if (e instanceof Error) return { success: false, message: e.message }
    return { success: false, message: "导出失败" }
  }
}

/**
 * 删除用户（管理员）
 *
 * P0-2 修复：DB 操作下沉到 data-access.deleteUserById，包含最后管理员保护。
 * P0-3 修复：客户端通过 Server Action 调用，不再用 fetch。
 */
export async function deleteUserAction(
  userId: string
): Promise<ActionState<void>> {
  try {
    await requirePermission(Permissions.USER_MANAGE)
    await deleteUserById(userId)
    revalidatePath("/admin/users")
    return { success: true, message: "用户已删除" }
  } catch (e) {
    if (e instanceof PermissionDeniedError) {
      return { success: false, message: e.message }
    }
    if (e instanceof Error) return { success: false, message: e.message }
    return { success: false, message: "删除用户失败" }
  }
}
