/**
 * 项目-模板绑定相关类型定义
 * 遵循前端开发规范的类型设计原则
 */

export interface ProjectTemplateBinding {
  id: string;
  project_id: string;
  template_id: string;
  binding_name?: string;
  description?: string;
  priority: number;
  is_active: boolean;
  binding_type: BindingType;
  binding_status: BindingStatus;
  metadata?: string;
  created_at: string;
  updated_at: string;
}

export enum BindingType {
  Primary = 'Primary',
  Secondary = 'Secondary',
  Reference = 'Reference',
  Test = 'Test',
}

export enum BindingStatus {
  Active = 'Active',
  Paused = 'Paused',
  Completed = 'Completed',
  Cancelled = 'Cancelled',
}

export interface CreateProjectTemplateBindingRequest {
  project_id: string;
  template_id: string;
  binding_name?: string;
  description?: string;
  priority?: number;
  binding_type: BindingType;
}

export interface UpdateProjectTemplateBindingRequest {
  binding_name?: string;
  description?: string;
  priority?: number;
  binding_type?: BindingType;
  binding_status?: BindingStatus;
  is_active?: boolean;
}

export interface ProjectTemplateBindingQueryParams {
  project_id?: string;
  template_id?: string;
  binding_type?: BindingType;
  binding_status?: BindingStatus;
  is_active?: boolean;
  limit?: number;
  offset?: number;
}

export interface ProjectTemplateBindingDetail {
  binding: ProjectTemplateBinding;
  project_name: string;
  template_name: string;
  template_description?: string;
}

export interface BatchCreateProjectTemplateBindingRequest {
  project_id: string;
  template_ids: string[];
  binding_type: BindingType;
  priority_start?: number;
}

export interface BatchDeleteProjectTemplateBindingRequest {
  binding_ids: string[];
}

// UI 相关类型
export interface ProjectTemplateBindingFormData {
  template_id: string;
  binding_name: string;
  description: string;
  priority: number;
  binding_type: BindingType;
}

export interface ProjectTemplateBindingListItem extends ProjectTemplateBindingDetail {
  // 扩展用于列表显示的字段
  binding_type_display: string;
  binding_status_display: string;
  is_primary: boolean;
  can_edit: boolean;
  can_delete: boolean;
}

// 绑定类型选项
export const BINDING_TYPE_OPTIONS = [
  { value: BindingType.Primary, label: '主要绑定', description: '项目的主要模板' },
  { value: BindingType.Secondary, label: '次要绑定', description: '项目的备用模板' },
  { value: BindingType.Reference, label: '参考绑定', description: '仅作为参考的模板' },
  { value: BindingType.Test, label: '测试绑定', description: '用于测试的模板' },
];

// 绑定状态选项
export const BINDING_STATUS_OPTIONS = [
  { value: BindingStatus.Active, label: '活跃', description: '正在使用' },
  { value: BindingStatus.Paused, label: '暂停', description: '暂时不使用' },
  { value: BindingStatus.Completed, label: '已完成', description: '已完成使用' },
  { value: BindingStatus.Cancelled, label: '已取消', description: '取消绑定' },
];

// 工具函数
export const getBindingTypeDisplay = (type: BindingType): string => {
  const option = BINDING_TYPE_OPTIONS.find(opt => opt.value === type);
  return option?.label || type;
};

export const getBindingStatusDisplay = (status: BindingStatus): string => {
  const option = BINDING_STATUS_OPTIONS.find(opt => opt.value === status);
  return option?.label || status;
};

export const getBindingTypeColor = (type: BindingType): string => {
  switch (type) {
    case BindingType.Primary:
      return 'bg-blue-100 text-blue-800';
    case BindingType.Secondary:
      return 'bg-green-100 text-green-800';
    case BindingType.Reference:
      return 'bg-yellow-100 text-yellow-800';
    case BindingType.Test:
      return 'bg-purple-100 text-purple-800';
    default:
      return 'bg-gray-100 text-gray-800';
  }
};

export const getBindingStatusColor = (status: BindingStatus): string => {
  switch (status) {
    case BindingStatus.Active:
      return 'bg-green-100 text-green-800';
    case BindingStatus.Paused:
      return 'bg-yellow-100 text-yellow-800';
    case BindingStatus.Completed:
      return 'bg-blue-100 text-blue-800';
    case BindingStatus.Cancelled:
      return 'bg-red-100 text-red-800';
    default:
      return 'bg-gray-100 text-gray-800';
  }
};

// 验证函数
export const validateBindingFormData = (data: Partial<ProjectTemplateBindingFormData>): string[] => {
  const errors: string[] = [];

  if (!data.template_id?.trim()) {
    errors.push('请选择模板');
  }

  if (data.binding_name && data.binding_name.length > 100) {
    errors.push('绑定名称不能超过100个字符');
  }

  if (data.description && data.description.length > 500) {
    errors.push('绑定描述不能超过500个字符');
  }

  if (data.priority !== undefined && (data.priority < 0 || data.priority > 999)) {
    errors.push('优先级必须在0-999之间');
  }

  return errors;
};

// 排序函数
export const sortBindingsByPriority = (bindings: ProjectTemplateBinding[]): ProjectTemplateBinding[] => {
  return [...bindings].sort((a, b) => {
    // 首先按优先级排序（数值越小优先级越高）
    if (a.priority !== b.priority) {
      return a.priority - b.priority;
    }
    // 然后按绑定类型排序（主要绑定优先）
    const typeOrder = {
      [BindingType.Primary]: 0,
      [BindingType.Secondary]: 1,
      [BindingType.Reference]: 2,
      [BindingType.Test]: 3,
    };
    if (typeOrder[a.binding_type] !== typeOrder[b.binding_type]) {
      return typeOrder[a.binding_type] - typeOrder[b.binding_type];
    }
    // 最后按创建时间排序（新的在前）
    return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
  });
};

// 过滤函数
export const filterBindings = (
  bindings: ProjectTemplateBinding[],
  filters: {
    binding_type?: BindingType;
    binding_status?: BindingStatus;
    is_active?: boolean;
    search?: string;
  }
): ProjectTemplateBinding[] => {
  return bindings.filter(binding => {
    if (filters.binding_type && binding.binding_type !== filters.binding_type) {
      return false;
    }
    if (filters.binding_status && binding.binding_status !== filters.binding_status) {
      return false;
    }
    if (filters.is_active !== undefined && binding.is_active !== filters.is_active) {
      return false;
    }
    if (filters.search) {
      const searchLower = filters.search.toLowerCase();
      return (
        binding.binding_name?.toLowerCase().includes(searchLower) ||
        binding.description?.toLowerCase().includes(searchLower)
      );
    }
    return true;
  });
};

// 统计函数
export const getBindingStats = (bindings: ProjectTemplateBinding[]) => {
  const total = bindings.length;
  const active = bindings.filter(b => b.is_active && b.binding_status === BindingStatus.Active).length;
  const primary = bindings.filter(b => b.binding_type === BindingType.Primary).length;
  const paused = bindings.filter(b => b.binding_status === BindingStatus.Paused).length;

  return {
    total,
    active,
    primary,
    paused,
    inactive: total - active,
  };
};
