/**
 * [MOCK-016] 运营代理模块DataSource
 * AI注意: 这是Mock实现，不是真实业务逻辑
 * 仅在USE_MOCK=true时启用 */

export interface Store {
  id: string;
  name: string;
  platform: string;
  status: 'ACTIVE' | 'INACTIVE' | 'SUSPENDED';
  region: string;
  currency: string;
}

export interface StoreBindingData {
  storeId: string;
  platform: string;
  apiKey: string;
  apiSecret: string;
  accessToken?: string;
  refreshToken?: string;
  expiresAt?: string;
  status: 'ACTIVE' | 'INACTIVE' | 'ERROR';
}

export type TaskStatus = 'PENDING' | 'RUNNING' | 'COMPLETED' | 'FAILED' | 'CANCELLED';
export type TaskType = 'PRICING' | 'LISTING' | 'AD_OPTIMIZATION';
export type TaskPriority = 'HIGH' | 'MEDIUM' | 'LOW';

export interface Task {
  id: string;
  storeId: string;
  merchantId: string;
  taskType: TaskType;
  priority: TaskPriority;
  status: TaskStatus;
  progress: number;
  createdAt: string;
  created_at: string;
  updated_at: string;
  completed_at?: string;
  startedAt?: string;
  completedAt?: string;
  error?: string;
  targetProducts: string[];
  constraints: {
    maxPrice?: number;
    minROI?: number;
    maxQuantity?: number;
  };
  description?: string;
  metadata: Record<string, any>;
  logs: Array<{
    timestamp: string;
    level: 'INFO' | 'WARN' | 'ERROR';
    message: string;
  }>;
}

export interface OperationAgentDataSource {
  getStores(): Promise<Store[]>;
  getStoreBindings(storeId: string): Promise<StoreBindingData[]>;
  createStoreBinding(data: Omit<StoreBindingData, 'status'>): Promise<StoreBindingData>;
  updateStoreBinding(id: string, data: Partial<StoreBindingData>): Promise<StoreBindingData | null>;
  deleteStoreBinding(id: string): Promise<boolean>;
  getTasks(params?: {
    storeId?: string;
    type?: TaskType;
    status?: TaskStatus;
    priority?: TaskPriority;
  }): Promise<Task[]>;
  createTask(data: Omit<Task, 'id' | 'status' | 'progress' | 'createdAt' | 'logs'>): Promise<Task>;
  updateTask(id: string, data: Partial<Task>): Promise<Task | null>;
  deleteTask(id: string): Promise<boolean>;
  startTask(id: string): Promise<Task | null>;
  stopTask(id: string): Promise<Task | null>;
  getTaskLogs(id: string): Promise<Task['logs']>;
}

export class OperationAgentDataSourceImpl implements OperationAgentDataSource {
  private stores: Store[] = [
    {
      id: '1',
      name: 'Amazon Store 1',
      platform: 'amazon',
      status: 'ACTIVE',
      region: 'US',
      currency: 'USD',
    },
    {
      id: '2',
      name: 'Shopee Store 1',
      platform: 'shopee',
      status: 'ACTIVE',
      region: 'SG',
      currency: 'SGD',
    },
  ];

  private storeBindings: StoreBindingData[] = [
    {
      storeId: '1',
      platform: 'amazon',
      apiKey: 'amazon-api-key-1',
      apiSecret: 'amazon-api-secret-1',
      accessToken: 'amazon-access-token-1',
      expiresAt: new Date(Date.now() + 3600000).toISOString(),
      status: 'ACTIVE',
    },
    {
      storeId: '2',
      platform: 'shopee',
      apiKey: 'shopee-api-key-1',
      apiSecret: 'shopee-api-secret-1',
      accessToken: 'shopee-access-token-1',
      expiresAt: new Date(Date.now() + 3600000).toISOString(),
      status: 'ACTIVE',
    },
  ];

  private tasks: Task[] = [
    {
      id: '1',
      storeId: '1',
      merchantId: 'merchant-1',
      taskType: 'PRICING',
      priority: 'HIGH',
      status: 'COMPLETED',
      progress: 100,
      createdAt: new Date(Date.now() - 3600000).toISOString(),
      created_at: new Date(Date.now() - 3600000).toISOString(),
      updated_at: new Date(Date.now() - 3480000).toISOString(),
      completed_at: new Date(Date.now() - 3480000).toISOString(),
      startedAt: new Date(Date.now() - 3540000).toISOString(),
      completedAt: new Date(Date.now() - 3480000).toISOString(),
      targetProducts: ['prod-1', 'prod-2', 'prod-3'],
      constraints: {
        maxPrice: 100,
        minROI: 0.2,
        maxQuantity: 1000,
      },
      description: '定价优化任务',
      metadata: {
        productCount: 100,
        strategy: 'competitive',
      },
      logs: [
        {
          timestamp: new Date(Date.now() - 3600000).toISOString(),
          level: 'INFO',
          message: 'Task started',
        },
        {
          timestamp: new Date(Date.now() - 3540000).toISOString(),
          level: 'INFO',
          message: 'Task completed successfully',
        },
      ],
    },
    {
      id: '2',
      storeId: '2',
      merchantId: 'merchant-2',
      taskType: 'LISTING',
      priority: 'MEDIUM',
      status: 'RUNNING',
      progress: 50,
      createdAt: new Date(Date.now() - 1800000).toISOString(),
      created_at: new Date(Date.now() - 1800000).toISOString(),
      updated_at: new Date(Date.now() - 1740000).toISOString(),
      startedAt: new Date(Date.now() - 1740000).toISOString(),
      targetProducts: ['prod-4', 'prod-5'],
      constraints: {
        maxPrice: 200,
        minROI: 0.15,
      },
      description: '商品上架任务',
      metadata: {
        productCount: 50,
        template: 'default',
      },
      logs: [
        {
          timestamp: new Date(Date.now() - 1800000).toISOString(),
          level: 'INFO',
          message: 'Task started',
        },
        {
          timestamp: new Date(Date.now() - 1740000).toISOString(),
          level: 'INFO',
          message: 'Processing products...',
        },
      ],
    },
  ];

  async getStores(): Promise<Store[]> {
    await new Promise(resolve => setTimeout(resolve, 300));
    return this.stores;
  }

  async getStoreBindings(storeId: string): Promise<StoreBindingData[]> {
    await new Promise(resolve => setTimeout(resolve, 300));
    return this.storeBindings.filter(binding => binding.storeId === storeId);
  }

  async createStoreBinding(data: Omit<StoreBindingData, 'id' | 'status'>): Promise<StoreBindingData> {
    await new Promise(resolve => setTimeout(resolve, 500));
    const newBinding: StoreBindingData = {
      ...data,
      status: 'ACTIVE',
    };
    this.storeBindings.push(newBinding);
    return newBinding;
  }

  async updateStoreBinding(id: string, data: Partial<StoreBindingData>): Promise<StoreBindingData | null> {
    await new Promise(resolve => setTimeout(resolve, 500));
    const index = this.storeBindings.findIndex(binding => binding.storeId === id);
    if (index === -1) return null;
    this.storeBindings[index] = { ...this.storeBindings[index], ...data };
    return this.storeBindings[index];
  }

  async deleteStoreBinding(id: string): Promise<boolean> {
    await new Promise(resolve => setTimeout(resolve, 300));
    const index = this.storeBindings.findIndex(binding => binding.storeId === id);
    if (index === -1) return false;
    this.storeBindings.splice(index, 1);
    return true;
  }

  async getTasks(params?: {
    storeId?: string;
    type?: TaskType;
    status?: TaskStatus;
    priority?: TaskPriority;
  }): Promise<Task[]> {
    await new Promise(resolve => setTimeout(resolve, 300));
    let filteredTasks = [...this.tasks];
    if (params?.storeId) {
      filteredTasks = filteredTasks.filter(task => task.storeId === params.storeId);
    }
    if (params?.type) {
      filteredTasks = filteredTasks.filter(task => task.taskType === params.type);
    }
    if (params?.status) {
      filteredTasks = filteredTasks.filter(task => task.status === params.status);
    }
    if (params?.priority) {
      filteredTasks = filteredTasks.filter(task => task.priority === params.priority);
    }
    return filteredTasks;
  }

  async createTask(data: Omit<Task, 'id' | 'status' | 'progress' | 'createdAt' | 'created_at' | 'updated_at' | 'logs'>): Promise<Task> {
    await new Promise(resolve => setTimeout(resolve, 500));
    const now = new Date().toISOString();
    const newTask: Task = {
      ...data,
      id: `${Date.now()}`,
      status: 'PENDING',
      progress: 0,
      createdAt: now,
      created_at: now,
      updated_at: now,
      logs: [],
    };
    this.tasks.unshift(newTask);
    return newTask;
  }

  async updateTask(id: string, data: Partial<Task>): Promise<Task | null> {
    await new Promise(resolve => setTimeout(resolve, 300));
    const index = this.tasks.findIndex(task => task.id === id);
    if (index === -1) return null;
    this.tasks[index] = { ...this.tasks[index], ...data };
    return this.tasks[index];
  }

  async deleteTask(id: string): Promise<boolean> {
    await new Promise(resolve => setTimeout(resolve, 300));
    const index = this.tasks.findIndex(task => task.id === id);
    if (index === -1) return false;
    this.tasks.splice(index, 1);
    return true;
  }

  async startTask(id: string): Promise<Task | null> {
    await new Promise(resolve => setTimeout(resolve, 500));
    const index = this.tasks.findIndex(task => task.id === id);
    if (index === -1) return null;
    this.tasks[index] = {
      ...this.tasks[index],
      status: 'RUNNING',
      startedAt: new Date().toISOString(),
      logs: [
        ...this.tasks[index].logs,
        {
          timestamp: new Date().toISOString(),
          level: 'INFO',
          message: 'Task started',
        },
      ],
    };
    return this.tasks[index];
  }

  async stopTask(id: string): Promise<Task | null> {
    await new Promise(resolve => setTimeout(resolve, 500));
    const index = this.tasks.findIndex(task => task.id === id);
    if (index === -1) return null;
    this.tasks[index] = {
      ...this.tasks[index],
      status: 'CANCELLED',
      completedAt: new Date().toISOString(),
      logs: [
        ...this.tasks[index].logs,
        {
          timestamp: new Date().toISOString(),
          level: 'INFO',
          message: 'Task cancelled',
        },
      ],
    };
    return this.tasks[index];
  }

  async getTaskLogs(id: string): Promise<Task['logs']> {
    await new Promise(resolve => setTimeout(resolve, 300));
    const task = this.tasks.find(task => task.id === id);
    return task?.logs || [];
  }
}

export const operationAgentDataSource = new OperationAgentDataSourceImpl();