/**
 * 证书系统 API
 */
import request from '@/api/request'

// 证书类型
export type CertificateType = 'course' | 'exam' | 'achievement'

// 证书模板
export interface CertificateTemplate {
  id: number
  name: string
  type: CertificateType
  background_url?: string
  is_active: boolean
}

// 证书信息
export interface Certificate {
  id: number
  certificate_no: string
  title: string
  description?: string
  type: CertificateType
  type_name: string
  issued_at: string
  valid_until?: string
  score?: number
  completion_rate?: number
  pdf_url?: string
  image_url?: string
  course_id?: number
  exam_id?: number
  badge_id?: number
  meta_data?: Record<string, any>
  template?: {
    id: number
    name: string
    background_url?: string
  }
  user?: {
    id: number
    username: string
    full_name?: string
  }
}

// 证书列表响应
export interface CertificateListResponse {
  items: Certificate[]
  total: number
  offset: number
  limit: number
}

// 验证结果
export interface VerifyResult {
  valid: boolean
  certificate_no: string
  title?: string
  type_name?: string
  issued_at?: string
  user?: {
    id: number
    username: string
    full_name?: string
  }
}

/**
 * 获取证书模板列表
 */
export function getCertificateTemplates(type?: CertificateType) {
  return request.get<CertificateTemplate[]>('/certificates/templates', {
    params: { cert_type: type }
  })
}

/**
 * 获取我的证书列表
 */
export function getMyCertificates(params?: {
  cert_type?: CertificateType
  offset?: number
  limit?: number
}) {
  return request.get<CertificateListResponse>('/certificates/me', { params })
}

/**
 * 获取指定用户的证书列表
 */
export function getUserCertificates(userId: number, params?: {
  cert_type?: CertificateType
  offset?: number
  limit?: number
}) {
  return request.get<CertificateListResponse>(`/certificates/user/${userId}`, { params })
}

/**
 * 获取证书详情
 */
export function getCertificateDetail(certId: number) {
  return request.get<Certificate>(`/certificates/${certId}`)
}

/**
 * 获取证书分享图片URL
 */
export function getCertificateImageUrl(certId: number): string {
  return `/api/v1/certificates/${certId}/image`
}

/**
 * 获取证书下载URL
 */
export function getCertificateDownloadUrl(certId: number): string {
  return `/api/v1/certificates/${certId}/download`
}

/**
 * 验证证书
 */
export function verifyCertificate(certNo: string) {
  return request.get<VerifyResult>(`/certificates/verify/${certNo}`)
}

/**
 * 颁发课程证书
 */
export function issueCoursCertificate(data: {
  course_id: number
  course_name: string
  completion_rate?: number
}) {
  return request.post<Certificate>('/certificates/issue/course', data)
}

/**
 * 颁发考试证书
 */
export function issueExamCertificate(data: {
  exam_id: number
  exam_name: string
  score: number
}) {
  return request.post<Certificate>('/certificates/issue/exam', data)
}
