import { http } from './http';
import { PlatformAccount, PlatformAccountStats } from '@/types/platform';

export interface PlatformAuthDataSource {
  list(filters?: { platform?: string; status?: string; shopId?: string }): Promise<PlatformAccount[]>;
  getById(id: string): Promise<PlatformAccount | null>;
  connect(data: { platform: string; accountName: string; accountId: string; shopId?: string; config?: Record<string, any> }): Promise<{ account: PlatformAccount; authUrl: string }>;
  refresh(id: string): Promise<{ success: boolean; message: string }>;
  disconnect(id: string): Promise<void>;
  delete(id: string): Promise<void>;
  getStats(): Promise<PlatformAccountStats>;
}

export class PlatformAuthApiDataSource implements PlatformAuthDataSource {
  async list(filters?: { platform?: string; status?: string; shopId?: string }): Promise<PlatformAccount[]> {
    const params = new URLSearchParams();
    if (filters?.platform) params.append('platform', filters.platform);
    if (filters?.status) params.append('status', filters.status);
    if (filters?.shopId) params.append('shopId', filters.shopId);
    
    const response = await http.get(`/api/platform-auth/list?${params.toString()}`);
    return response.data.data;
  }

  async getById(id: string): Promise<PlatformAccount | null> {
    const response = await http.get(`/api/platform-auth/${id}`);
    return response.data.data;
  }

  async connect(data: { platform: string; accountName: string; accountId: string; shopId?: string; config?: Record<string, any> }): Promise<{ account: PlatformAccount; authUrl: string }> {
    const response = await http.post('/api/platform-auth/connect', data);
    return response.data.data;
  }

  async refresh(id: string): Promise<{ success: boolean; message: string }> {
    const response = await http.post(`/api/platform-auth/refresh/${id}`);
    return response.data.data;
  }

  async disconnect(id: string): Promise<void> {
    await http.post(`/api/platform-auth/disconnect/${id}`);
  }

  async delete(id: string): Promise<void> {
    await http.delete(`/api/platform-auth/${id}`);
  }

  async getStats(): Promise<PlatformAccountStats> {
    const response = await http.get('/api/platform-auth/stats');
    return response.data.data;
  }
}

export class PlatformAuthMockDataSource implements PlatformAuthDataSource {
  private mockAccounts: PlatformAccount[] = [
    {
      id: '1',
      tenantId: 'tenant_1',
      platform: 'AMAZON',
      accountName: 'My Amazon Store',
      accountId: 'amazon_123',
      status: 'ACTIVE',
      lastSyncAt: '2024-01-15T10:30:00Z',
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: '2024-01-15T10:30:00Z',
    },
    {
      id: '2',
      tenantId: 'tenant_1',
      platform: 'SHOPIFY',
      accountName: 'my-shop.myshopify.com',
      accountId: 'shopify_456',
      status: 'ACTIVE',
      lastSyncAt: '2024-01-15T09:15:00Z',
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: '2024-01-15T09:15:00Z',
    },
    {
      id: '3',
      tenantId: 'tenant_1',
      platform: 'SHOPEE',
      accountName: 'My Shopee Shop',
      accountId: 'shopee_789',
      status: 'EXPIRED',
      lastSyncAt: '2023-12-01T08:00:00Z',
      createdAt: '2023-06-01T00:00:00Z',
      updatedAt: '2024-01-01T08:00:00Z',
    },
    {
      id: '4',
      tenantId: 'tenant_1',
      platform: 'EBAY',
      accountName: 'My eBay Store',
      accountId: 'ebay_101',
      status: 'INACTIVE',
      createdAt: '2024-01-10T00:00:00Z',
      updatedAt: '2024-01-10T00:00:00Z',
    },
  ];

  async list(filters?: { platform?: string; status?: string; shopId?: string }): Promise<PlatformAccount[]> {
    let result = [...this.mockAccounts];
    if (filters?.platform) {
      result = result.filter(a => a.platform === filters.platform);
    }
    if (filters?.status) {
      result = result.filter(a => a.status === filters.status);
    }
    return result;
  }

  async getById(id: string): Promise<PlatformAccount | null> {
    return this.mockAccounts.find(a => a.id === id) || null;
  }

  async connect(data: { platform: string; accountName: string; accountId: string; shopId?: string; config?: Record<string, any> }): Promise<{ account: PlatformAccount; authUrl: string }> {
    const account: PlatformAccount = {
      id: Date.now().toString(),
      tenantId: 'tenant_1',
      platform: data.platform,
      accountName: data.accountName,
      accountId: data.accountId,
      status: 'INACTIVE',
      shopId: data.shopId,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    this.mockAccounts.push(account);
    return {
      account,
      authUrl: `https://example.com/oauth/authorize?platform=${data.platform}`,
    };
  }

  async refresh(id: string): Promise<{ success: boolean; message: string }> {
    const account = this.mockAccounts.find(a => a.id === id);
    if (account) {
      account.status = 'ACTIVE';
      account.lastSyncAt = new Date().toISOString();
    }
    return { success: true, message: 'Token refreshed successfully' };
  }

  async disconnect(id: string): Promise<void> {
    const account = this.mockAccounts.find(a => a.id === id);
    if (account) {
      account.status = 'INACTIVE';
    }
  }

  async delete(id: string): Promise<void> {
    this.mockAccounts = this.mockAccounts.filter(a => a.id !== id);
  }

  async getStats(): Promise<PlatformAccountStats> {
    return {
      total: this.mockAccounts.length,
      active: this.mockAccounts.filter(a => a.status === 'ACTIVE').length,
      inactive: this.mockAccounts.filter(a => a.status === 'INACTIVE').length,
      expired: this.mockAccounts.filter(a => a.status === 'EXPIRED').length,
      error: this.mockAccounts.filter(a => a.status === 'ERROR').length,
    };
  }
}

export const platformAuthDataSource = process.env.REACT_APP_USE_MOCK === 'true'
  ? new PlatformAuthMockDataSource()
  : new PlatformAuthApiDataSource();
