import { logger } from '../../utils/logger';
import { IPlatformConnector, PlatformProduct, PublishResult } from './IPlatformConnector';
import axios from 'axios';

interface TemuProduct {
  goods_id: string;
  goods_name: string;
  goods_desc: string;
  price: number;
  currency: string;
  thumb_url: string;
  image_urls: string[];
  sku_list: Array<{
    sku_id: string;
    price: number;
    stock: number;
    spec_values: Record<string, string>;
  }>;
  cat_id: string;
  goods_properties: Record<string, any>;
}

interface TemuOrder {
  order_sn: string;
  order_status: number;
  create_time: number;
  buyer_info: {
    buyer_id: string;
    buyer_name: string;
  };
  item_list: Array<{
    goods_id: string;
    sku_id: string;
    quantity: number;
    price: number;
  }>;
  shipping_info: {
    address_line1: string;
    city: string;
    state: string;
    country: string;
    zip_code: string;
  };
  order_amount: number;
  currency: string;
}

export class TemuConnector implements IPlatformConnector {
  platformCode = 'TEMU';
  capabilities = {
    hasApi: true,
    supportsPriceSync: true,
    supportsInventorySync: true,
    supportsOrderPull: true
  };

  private apiBaseUrl = 'https://api.temu.com';
  private appKey = process.env.TEMU_APP_KEY || '';
  private appSecret = process.env.TEMU_APP_SECRET || '';

  async authorize(shopId: string): Promise<boolean> {
    logger.info(`[TemuConnector] Authorizing shop: ${shopId}`);
    return true;
  }

  async pullProducts(shopId: string, params?: { page?: number; pageSize?: number }): Promise<PlatformProduct[]> {
    logger.info(`[TemuConnector] Pulling products for shop: ${shopId}`);

    if (!this.appKey || this.appKey === '') {
      return this.getMockProducts();
    }

    try {
      const response = await axios.post(`${this.apiBaseUrl}/api/goods/search`, {
        mall_id: shopId,
        page: params?.page || 1,
        page_size: params?.pageSize || 50
      });

      const products: TemuProduct[] = response.data?.result?.goods_list || [];
      return products.map(this.mapToPlatformProduct);
    } catch (error) {
      logger.warn('[TemuConnector] API call failed, returning mock data');
      return this.getMockProducts();
    }
  }

  async pullOrders(shopId: string, params?: { startTime?: number; endTime?: number }): Promise<TemuOrder[]> {
    logger.info(`[TemuConnector] Pulling orders for shop: ${shopId}`);

    if (!this.appKey || this.appKey === '') {
      return this.getMockOrders();
    }

    try {
      const response = await axios.post(`${this.apiBaseUrl}/api/order/search`, {
        mall_id: shopId,
        start_time: params?.startTime || Math.floor(Date.now() / 1000) - 86400 * 7,
        end_time: params?.endTime || Math.floor(Date.now() / 1000)
      });

      return response.data?.result?.order_list || [];
    } catch (error) {
      logger.warn('[TemuConnector] Order API call failed, returning mock data');
      return this.getMockOrders();
    }
  }

  async pushListing(shopId: string, product: PlatformProduct): Promise<PublishResult> {
    logger.info(`[TemuConnector] Pushing listing to Temu: ${product.title}`);

    if (!this.appKey || this.appKey === '') {
      return {
        success: true,
        externalId: `TEMU-${Date.now()}`,
        publishUrl: `https://www.temu.com/product-TEMU-${Date.now()}.html`
      };
    }

    try {
      const temuProduct = this.mapFromPlatformProduct(product);
      const response = await axios.post(
        `${this.apiBaseUrl}/api/goods/create`,
        { mall_id: shopId, goods: temuProduct }
      );

      return {
        success: true,
        externalId: response.data?.result?.goods_id,
        publishUrl: `https://www.temu.com/product-${response.data?.result?.goods_id}.html`
      };
    } catch (error: any) {
      logger.error(`[TemuConnector] Push listing failed: ${error.message}`);
      return {
        success: false,
        error: error.message
      };
    }
  }

  async updatePrice(shopId: string, externalId: string, newPrice: number): Promise<boolean> {
    logger.info(`[TemuConnector] Updating price for ${externalId} to ${newPrice}`);

    if (!this.appKey || this.appKey === '') {
      return true;
    }

    try {
      await axios.post(`${this.apiBaseUrl}/api/goods/update_price`, {
        mall_id: shopId,
        goods_id: externalId,
        price: newPrice * 100
      });
      return true;
    } catch (error: any) {
      logger.error(`[TemuConnector] Update price failed: ${error.message}`);
      return false;
    }
  }

  async syncInventory(shopId: string, externalId: string, quantity: number): Promise<boolean> {
    logger.info(`[TemuConnector] Syncing inventory for ${externalId}: ${quantity}`);

    if (!this.appKey || this.appKey === '') {
      return true;
    }

    try {
      await axios.post(`${this.apiBaseUrl}/api/goods/update_stock`, {
        mall_id: shopId,
        goods_id: externalId,
        stock: quantity
      });
      return true;
    } catch (error: any) {
      logger.error(`[TemuConnector] Sync inventory failed: ${error.message}`);
      return false;
    }
  }

  async calculateShipping(shopId: string, params: { countryCode: string; weight: number }): Promise<{
    carrier: string;
    cost: number;
    currency: string;
    estimatedDays: number;
  }> {
    const baseCost = params.countryCode === 'US' ? 0 : 5.99;
    const weightCost = Math.max(0, (params.weight - 1) * 1.5);
    
    return {
      carrier: 'Temu Express',
      cost: baseCost + weightCost,
      currency: 'USD',
      estimatedDays: params.countryCode === 'US' ? 7 : 15
    };
  }

  private mapToPlatformProduct(temuProduct: TemuProduct): PlatformProduct {
    return {
      externalId: temuProduct.goods_id,
      title: temuProduct.goods_name,
      description: temuProduct.goods_desc,
      price: temuProduct.price / 100,
      currency: temuProduct.currency || 'USD',
      images: [temuProduct.thumb_url, ...temuProduct.image_urls],
      skus: temuProduct.sku_list.map(sku => ({
        skuId: sku.sku_id,
        price: sku.price / 100,
        stock: sku.stock,
        specs: sku.spec_values
      })),
      platform: 'TEMU',
      category: temuProduct.cat_id,
      attributes: temuProduct.goods_properties
    };
  }

  private mapFromPlatformProduct(product: PlatformProduct): Partial<TemuProduct> {
    return {
      goods_name: product.title,
      goods_desc: product.description || '',
      price: Math.round(product.price * 100),
      currency: product.currency || 'USD',
      thumb_url: product.images[0] || '',
      image_urls: product.images.slice(1),
      cat_id: product.category || '',
      goods_properties: product.attributes || {}
    };
  }

  private getMockProducts(): PlatformProduct[] {
    return [
      {
        externalId: 'TEMU_PROD_001',
        title: 'Temu Budget Wireless Earbuds',
        description: 'Affordable wireless earbuds with decent sound quality and 20h battery life. Great value for money!',
        price: 12.99,
        currency: 'USD',
        images: [
          'https://example.com/temu/earbuds-1.jpg',
          'https://example.com/temu/earbuds-2.jpg'
        ],
        skus: [
          { skuId: 'TEMU_SKU_001_W', price: 12.99, stock: 1000, specs: { color: 'White' } },
          { skuId: 'TEMU_SKU_001_B', price: 12.99, stock: 800, specs: { color: 'Black' } }
        ],
        platform: 'TEMU',
        category: 'Electronics',
        attributes: { brand: 'TemuBasic', features: 'Bluetooth 5.0' }
      },
      {
        externalId: 'TEMU_PROD_002',
        title: 'Kitchen Storage Organizer Set',
        description: 'Complete kitchen storage organizer set with 10 pieces. Perfect for organizing your pantry.',
        price: 19.99,
        currency: 'USD',
        images: ['https://example.com/temu/storage-set.jpg'],
        skus: [
          { skuId: 'TEMU_SKU_002', price: 19.99, stock: 500, specs: {} }
        ],
        platform: 'TEMU',
        category: 'Home & Kitchen'
      },
      {
        externalId: 'TEMU_PROD_003',
        title: 'Kids Art Supplies Kit',
        description: 'Complete art supplies kit for kids including crayons, markers, colored pencils and more.',
        price: 8.99,
        currency: 'USD',
        images: ['https://example.com/temu/art-kit.jpg'],
        skus: [
          { skuId: 'TEMU_SKU_003', price: 8.99, stock: 2000, specs: {} }
        ],
        platform: 'TEMU',
        category: 'Toys & Games'
      }
    ];
  }

  private getMockOrders(): TemuOrder[] {
    return [
      {
        order_sn: 'TEMU_ORDER_001',
        order_status: 2,
        create_time: Math.floor(Date.now() / 1000) - 7200,
        buyer_info: {
          buyer_id: 'TEMU_USER_001',
          buyer_name: 'temu_shopper'
        },
        item_list: [
          {
            goods_id: 'TEMU_PROD_001',
            sku_id: 'TEMU_SKU_001_W',
            quantity: 2,
            price: 1299
          },
          {
            goods_id: 'TEMU_PROD_002',
            sku_id: 'TEMU_SKU_002',
            quantity: 1,
            price: 1999
          }
        ],
        shipping_info: {
          address_line1: '456 Oak Avenue',
          city: 'New York',
          state: 'NY',
          country: 'US',
          zip_code: '10001'
        },
        order_amount: 4597,
        currency: 'USD'
      }
    ];
  }
}

export default TemuConnector;
