/**
 * [MOCK-COMMUNICATION] Omnichannel Communication DataSource
 */

export interface OmnichannelMessage {
  id: string;
  channelId: string;
  channelType: 'email' | 'chat' | 'social' | 'phone' | 'sms';
  customerId: string;
  customerName: string;
  content: string;
  direction: 'inbound' | 'outbound';
  status: 'pending' | 'processing' | 'completed' | 'failed';
  createdAt: string;
}

export interface CustomerProfile {
  id: string;
  customerId: string;
  channels: string[];
  tags: string[];
  preferences: Record<string, any>;
  lastInteractionAt?: string;
  totalInteractions: number;
}

export interface TeamTask {
  id: string;
  assignedTo: string;
  customerId: string;
  taskType: 'inquiry' | 'complaint' | 'follow_up' | 'escalation';
  priority: 'low' | 'medium' | 'high' | 'urgent';
  status: 'pending' | 'in_progress' | 'completed';
  description: string;
  dueDate?: string;
}

export interface IOmnichannelCommunicationDataSource {
  aggregateMessages(channels: Array<{ type: string; id: string }>): Promise<OmnichannelMessage[]>;
  autoReply(customerId: string, question: string, context: Record<string, any>): Promise<string>;
  createTeamTask(task: Omit<TeamTask, 'id'>): Promise<TeamTask>;
  updateCustomerProfile(customerId: string, updates: Partial<CustomerProfile>): Promise<CustomerProfile>;
  translateMessage(content: string, targetLanguage: string): Promise<string>;
}

class MockOmnichannelCommunicationDataSource implements IOmnichannelCommunicationDataSource {
  async aggregateMessages(channels: Array<{ type: string; id: string }>): Promise<OmnichannelMessage[]> {
    return [
      { id: 'msg_001', channelId: 'ch_001', channelType: 'email', customerId: 'cust_001', customerName: 'John Doe', content: 'I have a question about my order', direction: 'inbound', status: 'pending', createdAt: new Date().toISOString() },
      { id: 'msg_002', channelId: 'ch_002', channelType: 'chat', customerId: 'cust_002', customerName: 'Jane Smith', content: 'When will my order arrive?', direction: 'inbound', status: 'pending', createdAt: new Date().toISOString() },
    ];
  }

  async autoReply(customerId: string, question: string, context: Record<string, any>): Promise<string> {
    return 'Thank you for your inquiry. Our customer service team will assist you shortly.';
  }

  async createTeamTask(task: Omit<TeamTask, 'id'>): Promise<TeamTask> {
    return { ...task, id: `task_${Date.now()}` };
  }

  async updateCustomerProfile(customerId: string, updates: Partial<CustomerProfile>): Promise<CustomerProfile> {
    return { id: `profile_${customerId}`, customerId, channels: [], tags: [], preferences: {}, totalInteractions: 0, ...updates };
  }

  async translateMessage(content: string, targetLanguage: string): Promise<string> {
    return `[Translated to ${targetLanguage}]: ${content}`;
  }
}

class ApiOmnichannelCommunicationDataSource implements IOmnichannelCommunicationDataSource {
  private baseUrl = '/api/omnichannel';

  async aggregateMessages(channels: Array<{ type: string; id: string }>): Promise<OmnichannelMessage[]> {
    const res = await fetch(`${this.baseUrl}/communication/aggregate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ channels }),
    });
    const data = await res.json();
    return data.data;
  }

  async autoReply(customerId: string, question: string, context: Record<string, any>): Promise<string> {
    const res = await fetch(`${this.baseUrl}/communication/auto-reply`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ customerId, question, context }),
    });
    const data = await res.json();
    return data.data.reply;
  }

  async createTeamTask(task: Omit<TeamTask, 'id'>): Promise<TeamTask> {
    const res = await fetch(`${this.baseUrl}/communication/team-task`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(task),
    });
    const data = await res.json();
    return data.data;
  }

  async updateCustomerProfile(customerId: string, updates: Partial<CustomerProfile>): Promise<CustomerProfile> {
    const res = await fetch(`${this.baseUrl}/communication/customer/${customerId}/profile`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updates),
    });
    const data = await res.json();
    return data.data;
  }

  async translateMessage(content: string, targetLanguage: string): Promise<string> {
    const res = await fetch(`${this.baseUrl}/communication/translate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ content, targetLanguage }),
    });
    const data = await res.json();
    return data.data.translated;
  }
}

const useMock = process.env.REACT_APP_USE_MOCK === 'true';
export const omnichannelCommunicationDataSource: IOmnichannelCommunicationDataSource = useMock
  ? new MockOmnichannelCommunicationDataSource()
  : new ApiOmnichannelCommunicationDataSource();
