import { postgrestGet, postgrestPut, postgrestPost, type PostgrestParams } from '../postgrest-client';
import { formatDate } from '../../utils';
// 配置项接口
export interface ConfigItem {
  id: number;
  name: string;
  type: string;
  description: string;
  environment: string;
  config: Record<string, unknown>;
  remark: string;
  is_active: boolean;
  version: string;
  created_by: number;
  created_at: string;
  updated_at: string;
}


  
/**
 * 从不同格式的 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 async function getConfigLists(params: {
  name?: string;
  type?: string;
  environment?: string;
  is_active?: boolean;
  page?: number;
  pageSize?: number;
}): Promise<{data: ConfigItem[]; total: number; error?: never} | {data?: never; error: string}> {
  try {
    const { 
      name, 
      type, 
      environment, 
      is_active, 
      page = 1, 
      pageSize = 10 
    } = params;
    
    // 构建查询参数
    const queryParams: PostgrestParams = {
      select: '*',
      order: 'created_at.desc',
      limit: pageSize,
      offset: (page-1)*pageSize,
      filter: {} as Record<string, string>,
      headers: {
        'Prefer': 'count=exact'
      }
    };

    // 添加筛选条件
    const filter: Record<string, string> = {};
    if (name) {
      filter['name'] = `ilike.%${name}%`;
    }
    if (type) {
      filter['type'] = `eq.${type}`;
    }
    if (environment) {
      filter['environment'] = `eq.${environment}`;
    }
    if (is_active !== undefined) {
      filter['is_active'] = `eq.${is_active}`;
    }
    queryParams.filter = filter;

    // 获取数据
    const response = await postgrestGet<ConfigItem[]>('configurations', queryParams);

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

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

    // 格式化日期
    const formattedData = data.map(item => ({
      ...item,
      created_at: formatDate(item.created_at),
      updated_at: formatDate(item.updated_at)
    }));

    // 从响应头中获取总数
    let totalCount = 0;
    const responseWithHeaders = response as { data: ConfigItem[]; headers: Record<string, string> };
    if (responseWithHeaders.headers) {
      const rangeHeader = responseWithHeaders.headers['content-range'];
      if (rangeHeader) {
        const total = rangeHeader.split('/')[1];
        if (total !== '*') {
          totalCount = parseInt(total, 10);
        }
      }
    }

    return {
      data: formattedData,
      total: totalCount
    };
  } catch (error) {
    console.error('获取配置列表失败:', error);
    return { error: error instanceof Error ? error.message : '获取配置列表失败' };
  }
}

// 获取配置类型和环境选项
export async function getConfigOptions(): Promise<{data: {types: string[]; environments: string[]}; error?: never} | {data?: never; error: string}> {
  try {
    // 获取类型选项
    const typeResponse = await postgrestGet<{type: string}[]>('configurations', {
      select: 'type'
    });

    if (typeResponse.error) {
      return { error: typeResponse.error };
    }

    const typesData = extractApiData<{type: string}[]>(typeResponse.data);
    if (!typesData) {
      return { error: '获取类型选项失败' };
    }

    // 获取环境选项
    const envResponse = await postgrestGet<{environment: string}[]>('configurations', {
      select: 'environment'
    });

    if (envResponse.error) {
      return { error: envResponse.error };
    }

    const envData = extractApiData<{environment: string}[]>(envResponse.data);
    if (!envData) {
      return { error: '获取环境选项失败' };
    }

    // 手动去重
    const types = [...new Set(typesData.map(item => item.type))];
    const environments = [...new Set(envData.map(item => item.environment))];

    return {
      data: {
        types,
        environments
      }
    };
  } catch (error) {
    console.error('获取配置选项失败:', error);
    return { error: error instanceof Error ? error.message : '获取配置选项失败' };
  }
}

// 获取配置详情
export async function getConfigDetail(id: string): Promise<{data: ConfigItem; error?: never} | {data?: never; error: string}> {
  try {
    const response = await postgrestGet<ConfigItem[]>('configurations', {
      filter: {
        'id': `eq.${id}`
      }
    });

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

    const data = extractApiData<ConfigItem[]>(response.data);
    if (!data || data.length === 0) {
      return { error: '未找到配置' };
    }

    const config = data[0];
    return {
      data: {
        ...config,
        created_at: formatDate(config.created_at),
        updated_at: formatDate(config.updated_at)
      }
    };
  } catch (error) {
    console.error('获取配置详情失败:', error);
    return { error: error instanceof Error ? error.message : '获取配置详情失败' };
  }
}

// 创建配置
export async function createConfig(data: {
  name: string;
  type: string;
  environment: string;
  config: Record<string, unknown>;
  is_active: boolean;
  remark?: string;
}): Promise<{data: ConfigItem; error?: never} | {data?: never; error: string}> {
  try {
    const response = await postgrestPost<ConfigItem, typeof data>('configurations', data);

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

    const createdData = extractApiData<ConfigItem>(response.data);
    if (!createdData) {
      return { error: '创建配置失败' };
    }

    return {
      data: {
        ...createdData,
        created_at: formatDate(createdData.created_at),
        updated_at: formatDate(createdData.updated_at)
      }
    };
  } catch (error) {
    console.error('创建配置失败:', error);
    return { error: error instanceof Error ? error.message : '创建配置失败' };
  }
}

// 更新配置
export async function updateConfig(id: string, data: {
  name: string;
  type: string;
  environment: string;
  config: Record<string, unknown>;
  is_active: boolean;
  remark?: string;
}): Promise<{data: ConfigItem; error?: never} | {data?: never; error: string}> {
  try {
    const response = await postgrestPut<ConfigItem, typeof data>('configurations', data, {
      id: id.toString()
    });

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

    const updatedData = extractApiData<ConfigItem>(response.data);
    if (!updatedData) {
      return { error: '更新配置失败' };
    }

    return {
      data: {
        ...updatedData,
        created_at: formatDate(updatedData.created_at),
        updated_at: formatDate(updatedData.updated_at)
      }
    };
  } catch (error) {
    console.error('更新配置失败:', error);
    return { error: error instanceof Error ? error.message : '更新配置失败' };
  }
}

// 更新配置状态
export async function updateConfigStatus(id: number, is_active: boolean): Promise<{success: boolean; error?: string}> {
  try {
    const response = await postgrestPut<ConfigItem, {is_active: boolean}>(
      'configurations',
      { is_active },
      { id: id.toString() }
    );

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

    const updatedData = extractApiData<ConfigItem>(response.data);
    if (!updatedData) {
      return { success: false, error: '更新配置状态失败' };
    }

    return { success: true };
  } catch (error) {
    console.error('更新配置状态失败:', error);
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '更新配置状态失败' 
    };
  }
}
