import { postgrestGet, postgrestPut, postgrestPost, type PostgrestParams } from '../postgrest-client';
import dayjs from 'dayjs';

/**
 * 格式化日期
 * @param dateString 日期字符串
 * @returns 格式化后的日期字符串
 */
function formatDate(dateString: string): string {
    if (!dateString) return '';
    try {
      return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
    } catch (error) {
      console.error('日期格式化失败:', error);
      return dateString;
    }
}

  
/**
 * 从不同格式的 API 响应中提取数据
 * @param responseData API 响应数据
 * @returns 提取后的数据或 null
 */
function extractApiData<T>(responseData: unknown): T | null {
    if (!responseData) return null;

    // 格式1: { code: number, msg: string, data: T }
    if (typeof responseData === 'object' && responseData !== null && 
        'code' in responseData && 
        'data' in responseData && 
        (responseData as { data: unknown }).data) {
        return (responseData as { data: T }).data;
    }

    // 格式2: 直接是数据对象
    return responseData as T;
}

// 文档状态枚举
export enum DocumentStatus {
  CUTTING = "Cutting",
  EXTRACTIONING = "extractioning",
  REVIEWING = "reviewing",
  COMPLETED = "completed"
}

// 文档类型接口
export interface DocumentType {
  id: number;
  name: string;
}

// 提取结果接口
interface ExtractedResult {
  [key: string]: unknown;
}

// 摘要接口
interface Summary {
  [key: string]: unknown;
}

// 文档接口
export interface Document {
  id: number;
  name: string;
  type_id: number;
  file_size: number;
  status: DocumentStatus;
  created_at: string;
  document_number?: string;
  path?: string;
  storage_type?: string;
  is_test_document?: boolean;
  evaluation_level?: string;
  ocr_result?: Record<string, string>;
  extracted_results?: ExtractedResult;
  sumary?: Summary;
  remark?: string;
}

/**
 * 获取当天的文档列表
 * @returns 文档列表
 */
export async function getTodayDocuments(): Promise<{data: Document[]; error?: never} | {data?: never; error: string; status?: number}> {
  try {
    const today = dayjs().startOf('day').format('YYYY-MM-DD');
    console.log('查询当天文档，日期范围:', today);
    
    const params: PostgrestParams = {
      select: `
        id,
        name,
        type_id,
        file_size,
        status,
        created_at,
        document_number,
        path,
        storage_type,
        is_test_document,
        evaluation_level,
        ocr_result,
        extracted_results,
        sumary,
        remark
      `,
      order: 'created_at.desc',
      filter: {
        'created_at': `gte.${today}`
      }
    };

    // console.log('发送请求参数:', params);
    const response = await postgrestGet<Document[]>('documents', params);
    // console.log('API 响应:', response);

    if (response.error) {
      console.error('API 返回错误:', response.error);
      return { error: response.error, status: response.status };
    }

    const extractedData = extractApiData<Document[]>(response.data);
    // console.log('提取后的数据:', extractedData);
    
    if (!extractedData) {
      console.error('数据提取失败');
      return { error: '获取数据失败', status: 500 };
    }

    return { data: extractedData };
  } catch (error) {
    console.error('获取当天文档列表失败:', error);
    return { 
      error: error instanceof Error ? error.message : '获取当天文档列表失败',
      status: 500
    };
  }
}

/**
 * 获取文档类型列表
 * @returns 文档类型列表
 */
export async function getDocumentTypes(): Promise<{data: DocumentType[]; error?: never} | {data?: never; error: string; status?: number}> {
  try {
    const params: PostgrestParams = {
      select: 'id, name'
    };

    const response = await postgrestGet<DocumentType[]>('document_types', params);

    if (response.error) {
      return { error: response.error, status: response.status };
    }

    const extractedData = extractApiData<DocumentType[]>(response.data);
    if (!extractedData) {
      return { error: '获取数据失败', status: 500 };
    }

    return { data: extractedData };
  } catch (error) {
    console.error('获取文档类型列表失败:', error);
    return { 
      error: error instanceof Error ? error.message : '获取文档类型列表失败',
      status: 500
    };
  }
}

/**
 * 获取指定文档的状态
 * @param documentIds 文档ID列表
 * @returns 文档状态列表
 */
export async function getDocumentsStatus(documentIds: number[]): Promise<{data: Document[]; error?: never} | {data?: never; error: string; status?: number}> {
  try {
    if (!documentIds || documentIds.length === 0) {
      return { data: [] };
    }

    const params: PostgrestParams = {
      select: 'id, status',
      filter: {
        'id': `in.(${documentIds.join(',')})`
      }
    };

    const response = await postgrestGet<Document[]>('documents', params);

    if (response.error) {
      return { error: response.error, status: response.status };
    }

    const extractedData = extractApiData<Document[]>(response.data);
    if (!extractedData) {
      return { error: '获取数据失败', status: 500 };
    }

    return { data: extractedData };
  } catch (error) {
    console.error('获取文档状态失败:', error);
    return { 
      error: error instanceof Error ? error.message : '获取文档状态失败',
      status: 500
    };
  }
}