import { http } from './http';

export type ActorType = 'AI' | 'USER' | 'SYSTEM';
export type BusinessType = 'TOC' | 'TOB';

export interface OperationLogItem {
  id: number;
  tenant_id: string;
  shop_id?: string;
  task_id?: string;
  trace_id: string;
  user_id: string;
  role_code?: string;
  module: string;
  action: string;
  resource_type: string;
  resource_id?: string;
  before_snapshot?: any;
  after_snapshot?: any;
  result: 'success' | 'failed';
  error_code?: string;
  error_message?: string;
  client_ip?: string;
  user_agent?: string;
  source: 'console' | 'extension' | 'node';
  created_at: string;
  loop?: string;
  loop_name?: string;
  stage?: string;
  stage_name?: string;
  before_state?: string;
  after_state?: string;
  actor?: ActorType;
  actor_id?: string;
  actor_name?: string;
}

export interface OperationLogQuery {
  loop?: string;
  stage?: string;
  actor?: ActorType;
  actor_id?: string;
  user_id?: string;
  resource_id?: string;
  trace_id?: string;
  action?: string;
  module?: string;
  tenant_id?: string;
  shop_id?: string;
  keyword?: string;
  limit?: number;
  offset?: number;
  startDate?: string;
  endDate?: string;
}

export interface OperationLogResponse {
  logs: OperationLogItem[];
  total: number;
}

export interface OperationLogDataSource {
  list(query?: OperationLogQuery): Promise<OperationLogResponse>;
  getById(id: number): Promise<OperationLogItem>;
  getByTraceId(traceId: string): Promise<OperationLogItem[]>;
}

class OperationLogApiDataSource implements OperationLogDataSource {
  async list(query: OperationLogQuery = {}) {
    const response = await http.get('/api/audit/timeline', { params: query });
    return response.data.data;
  }

  async getById(id: number) {
    const response = await http.get(`/api/audit/log/${id}`);
    return response.data.data;
  }

  async getByTraceId(traceId: string) {
    const response = await http.get('/api/audit/timeline', { params: { traceId } });
    return response.data.data.logs;
  }
}

class OperationLogMockDataSource implements OperationLogDataSource {
  private logs: OperationLogItem[] = [
    {
      id: 1,
      tenant_id: 'T001',
      shop_id: 'S001',
      trace_id: 'TRX-001',
      user_id: 'U001',
      module: 'OrderFulfillment',
      action: 'ORDER_CONFIRM',
      resource_type: 'ORDER',
      resource_id: 'ORD-001',
      result: 'success',
      source: 'node',
      created_at: new Date(Date.now() - 300000).toISOString(),
      loop: 'OrderFulfillment',
      loop_name: '订单履约',
      stage: 'ORDER_CONFIRM',
      stage_name: '订单确认',
      before_state: 'PENDING',
      after_state: 'CONFIRMED',
      actor: 'SYSTEM',
      actor_name: 'System',
    },
    {
      id: 2,
      tenant_id: 'T001',
      shop_id: 'S001',
      trace_id: 'TRX-001',
      user_id: 'U001',
      module: 'OrderFulfillment',
      action: 'ORDER_AUDIT',
      resource_type: 'ORDER',
      resource_id: 'ORD-001',
      result: 'success',
      source: 'node',
      created_at: new Date(Date.now() - 180000).toISOString(),
      loop: 'OrderFulfillment',
      loop_name: '订单履约',
      stage: 'ORDER_AUDIT',
      stage_name: '订单审核',
      before_state: 'CONFIRMED',
      after_state: 'AUDITED',
      actor: 'AI',
      actor_id: 'AI-001',
      actor_name: 'AI决策引擎',
      after_snapshot: { aiSuggestion: '订单金额$299，低于阈值，自动通过', confidence: 0.95 },
    },
    {
      id: 3,
      tenant_id: 'T001',
      shop_id: 'S001',
      trace_id: 'TRX-002',
      user_id: 'admin',
      module: 'OrderFulfillment',
      action: 'WAREHOUSE_ASSIGN',
      resource_type: 'ORDER',
      resource_id: 'ORD-002',
      result: 'success',
      source: 'console',
      created_at: new Date(Date.now() - 60000).toISOString(),
      loop: 'OrderFulfillment',
      loop_name: '订单履约',
      stage: 'WAREHOUSE_ASSIGN',
      stage_name: '分仓',
      before_state: 'AUDITED',
      after_state: 'WAREHOUSE_ASSIGNED',
      actor: 'USER',
      actor_id: 'U001',
      actor_name: 'admin@company.com',
      after_snapshot: { warehouse: 'WH-SH-01', warehouseName: '上海仓' },
    },
  ];

  async list(query: OperationLogQuery = {}) {
    let filtered = [...this.logs];

    if (query.loop) {
      filtered = filtered.filter(log => log.loop === query.loop);
    }
    if (query.stage) {
      filtered = filtered.filter(log => log.stage === query.stage);
    }
    if (query.actor) {
      filtered = filtered.filter(log => log.actor === query.actor);
    }
    if (query.actor_id) {
      filtered = filtered.filter(log => log.actor_id === query.actor_id);
    }
    if (query.user_id) {
      filtered = filtered.filter(log => log.user_id === query.user_id);
    }
    if (query.resource_id) {
      filtered = filtered.filter(log => log.resource_id === query.resource_id);
    }
    if (query.trace_id) {
      filtered = filtered.filter(log => log.trace_id === query.trace_id);
    }
    if (query.module) {
      filtered = filtered.filter(log => log.module === query.module);
    }
    if (query.tenant_id) {
      filtered = filtered.filter(log => log.tenant_id === query.tenant_id);
    }
    if (query.shop_id) {
      filtered = filtered.filter(log => log.shop_id === query.shop_id);
    }
    if (query.keyword) {
      const keyword = query.keyword.toLowerCase();
      filtered = filtered.filter(log => 
        (log.module && log.module.toLowerCase().includes(keyword)) ||
        (log.action && log.action.toLowerCase().includes(keyword)) ||
        (log.actor_name && log.actor_name.toLowerCase().includes(keyword)) ||
        (log.trace_id && log.trace_id.toLowerCase().includes(keyword)) ||
        (log.error_message && log.error_message.toLowerCase().includes(keyword))
      );
    }

    const limit = query.limit || 50;
    const offset = query.offset || 0;

    return {
      logs: filtered.slice(offset, offset + limit),
      total: filtered.length,
    };
  }

  async getById(id: number) {
    const log = this.logs.find(l => l.id === id);
    if (!log) throw new Error('Log not found');
    return log;
  }

  async getByTraceId(traceId: string) {
    return this.logs.filter(log => log.trace_id === traceId);
  }
}

const useMock = process.env.NODE_ENV === 'development' || process.env.REACT_APP_USE_MOCK === 'true';
export const OperationLogDataSource: OperationLogDataSource = useMock
  ? new OperationLogMockDataSource()
  : new OperationLogApiDataSource();

export const LOOP_OPTIONS = [
  { value: 'OrderFulfillment', label: '订单履约' },
  { value: 'ProductManagement', label: '商品管理' },
  { value: 'AIAutomation', label: 'AI自动化' },
  { value: 'Finance', label: '财务结算' },
  { value: 'Inventory', label: '库存管理' },
  { value: 'AfterSales', label: '售后逆向' },
];

export const STAGE_OPTIONS: Record<string, Array<{ value: string; label: string }>> = {
  OrderFulfillment: [
    { value: 'ORDER_FETCH', label: '订单获取' },
    { value: 'ORDER_CONFIRM', label: '订单确认' },
    { value: 'ORDER_AUDIT', label: '订单审核' },
    { value: 'WAREHOUSE_ASSIGN', label: '分仓' },
    { value: 'DELIVERY', label: '发货' },
    { value: 'SIGN_IN', label: '签收' },
  ],
  AIAutomation: [
    { value: 'DATA_COLLECTION', label: '数据收集' },
    { value: 'AI_SUGGESTION', label: 'AI建议' },
    { value: 'HUMAN_REVIEW', label: '人工确认' },
    { value: 'EXECUTION', label: '执行' },
    { value: 'LOGGING', label: '日志记录' },
    { value: 'FEEDBACK', label: '反馈优化' },
  ],
};

export const ACTOR_OPTIONS = [
  { value: 'AI', label: 'AI' },
  { value: 'USER', label: '人工' },
  { value: 'SYSTEM', label: '系统' },
];

export const ACTION_OPTIONS = [
  { value: 'CREATE', label: '创建' },
  { value: 'UPDATE', label: '更新' },
  { value: 'DELETE', label: '删除' },
  { value: 'APPROVE', label: '审批通过' },
  { value: 'REJECT', label: '审批拒绝' },
  { value: 'EXECUTE', label: '执行' },
];