/**
 * 身份认证状态管理
 * 处理用户身份认证申请、状态查询等功能
 */

import { create } from 'zustand';
import { verificationService } from '@/services/auth';
import {
  VerificationStatusDTO,
  VerificationRecordDTO,
  SubmitVerificationRequest,
  UserIdentity,
  VerificationStatus,
} from '../../types/dto';

interface VerificationState {
  // 状态
  status: VerificationStatusDTO | null;
  records: VerificationRecordDTO[];
  isLoading: boolean;
  error: string | null;
  hasFetchedStatus: boolean;

  // 操作
  fetchStatus: () => Promise<void>;
  fetchRecords: (page?: number, pageSize?: number) => Promise<void>;
  submitVerification: (data: SubmitVerificationRequest) => Promise<boolean>;
  clearError: () => void;
  reset: () => void;
}

export const useVerificationStore = create<VerificationState>((set, get) => ({
  status: null,
  records: [],
  isLoading: false,
  error: null,
  hasFetchedStatus: false,

  // 获取认证状态
  fetchStatus: async () => {
    set({ isLoading: true, error: null });
    try {
      const status = await verificationService.getVerificationStatus();
      set({ status, isLoading: false, hasFetchedStatus: true });
    } catch (error: any) {
      set({
        isLoading: false,
        error: error?.message || '获取认证状态失败',
        hasFetchedStatus: true,
      });
    }
  },

  // 获取认证记录
  fetchRecords: async (page = 1, pageSize = 10) => {
    set({ isLoading: true, error: null });
    try {
      const result = await verificationService.getVerificationRecords(page, pageSize);
      if (result) {
        set({ records: result.list, isLoading: false });
      }
    } catch (error: any) {
      set({
        isLoading: false,
        error: error?.message || '获取认证记录失败',
      });
    }
  },

  // 提交认证申请
  submitVerification: async (data: SubmitVerificationRequest) => {
    set({ isLoading: true, error: null });
    try {
      const result = await verificationService.submitVerification(data);
      if (result) {
        // 提交成功后刷新状态
        await get().fetchStatus();
        set({ isLoading: false });
        return true;
      }
      return false;
    } catch (error: any) {
      set({
        isLoading: false,
        error: error?.message || '提交认证申请失败',
      });
      return false;
    }
  },

  // 清除错误
  clearError: () => set({ error: null }),

  // 重置状态
  reset: () => set({
    status: null,
    records: [],
    isLoading: false,
    error: null,
    hasFetchedStatus: false,
  }),
}));

// 导出便捷 hooks
export const useVerificationStatus = () => useVerificationStore((state) => state.status);
export const useIsVerified = () => {
  const status = useVerificationStore((state) => state.status);
  return status?.verification_status === 'approved';
};
export const useHasPendingVerification = () => {
  const status = useVerificationStore((state) => state.status);
  return status?.has_pending_request || status?.verification_status === 'pending';
};
export const useVerificationLoading = () => useVerificationStore((state) => state.isLoading);
