/**
 * LikeShop 适配器
 * 
 * LikeShop是新兴的开源电商系统
 * 支持从 LikeShop 免费版 迁移到 LiteMall
 * 
 * 关键表:
 *   ls_goods → 商品
 *   ls_category → 分类
 *   ls_user → 用户
 */

const PlatformAdapter = require('../adapter');

class LikeShopAdapter extends PlatformAdapter {
  constructor() {
    super({
      name: 'likeshop',
      label: 'LikeShop 免费版',
      version: '1.0',
      description: '支持LikeShop开源版商品/分类/用户数据迁移',
      icon: '💜',
      formats: ['sql', 'json'],
    });
    
    this.productFields = {
      'name': 'name',
      'code': null,
      'image': 'image',
      'video': 'video',
      'category_id': 'category_id',
      'price': 'price',
      'market_price': 'original_price',
      'cost_price': 'cost_price',
      'stock': 'stock',
      'sales_actual': 'sales',
      'unit_name': 'unit',
      'content': 'description',
      'status': 'status',
      'is_new': 'is_new',
      'is_hot': 'is_hot',
      'is_best': 'is_recommend',
      'weigh': 'sort',
      'create_time': { target: 'created_at', transform: v => v ? new Date(v * 1000).toISOString() : null },
      'update_time': { target: 'updated_at', transform: v => v ? new Date(v * 1000).toISOString() : null },
    };
  }

  detect(input) {
    const content = input.content || '';
    if (!content) return 0;
    
    let score = 0;
    
    if (input.type === 'sql') {
      if (content.includes('ls_goods') || content.includes('likeshop_goods')) score += 0.25;
      if (content.includes('ls_category') || content.includes('likeshop_category')) score += 0.2;
      if (content.includes('ls_user') || content.includes('likeshop_user')) score += 0.2;
      // LikeShop特徵: goods表有weigh字段（排序用）
      if (content.includes('`weigh`') && content.includes('`ls_goods`')) score += 0.35;
    }
    
    if (input.type === 'json') {
      try {
        const data = JSON.parse(content);
        if (data.products?.[0]?.weigh !== undefined) score += 0.3;
        if (data.products?.[0]?.sales_actual !== undefined) score += 0.2;
      } catch (e) { /* ignore */ }
    }
    
    return Math.min(score, 1);
  }

  async convert(input) {
    if (input.type === 'sql') return this._convertFromSql(input.content);
    if (input.type === 'json') return this._convertFromJson(input.content);
    throw new Error('不支持的格式');
  }

  _convertFromSql(sqlContent) {
    const data = { products: [], categories: [], users: [] };
    const tables = this._parseSqlTables(sqlContent);
    
    const now = new Date().toISOString();

    // 分类: ls_category 或 likeshop_category
    const catRows = tables['ls_category'] || tables['likeshop_category'] || [];
    for (const row of catRows) {
      data.categories.push({
        id: row.id,
        pid: row.pid || 0,
        name: row.name,
        sort: row.sort || 0,
        status: row.is_show !== undefined ? (row.is_show === 1 ? 1 : 0) : 1,
        icon: row.image || '',
        created_at: now,
        updated_at: now,
      });
    }

    // 商品: ls_goods 或 likeshop_goods
    const prodRows = tables['ls_goods'] || tables['likeshop_goods'] || [];
    for (const row of prodRows) {
      const product = {};
      for (const [srcKey, target] of Object.entries(this.productFields)) {
        if (target && row[srcKey] !== undefined) {
          if (typeof target === 'string') {
            product[target] = row[srcKey];
          } else if (target.transform) {
            product[target.target] = target.transform(row[srcKey]);
          }
        }
      }
      
      // 处理多图（图片可能是JSON数组）
      if (row.images) {
        try {
          const parsed = JSON.parse(row.images);
          product.images = Array.isArray(parsed) ? parsed.join(',') : row.images;
        } catch {
          product.images = row.images;
        }
      }
      
      if (!product.status) product.status = 1;
      if (!product.unit) product.unit = '件';
      if (!product.created_at) product.created_at = now;
      if (!product.updated_at) product.updated_at = now;
      
      data.products.push(product);
    }

    // 用户: ls_user 或 likeshop_user
    const userRows = tables['ls_user'] || tables['likeshop_user'] || [];
    for (const row of userRows) {
      data.users.push({
        id: row.id,
        nickname: row.nickname || '',
        phone: row.mobile || row.phone || '',
        avatar: row.avatar || '',
        level_id: row.level || 0,
        balance: row.user_money || 0,
        points: row.integral || 0,
        experience: row.experience || 0,
        status: row.status || 1,
        password: row.password || '$2b$10$default',
        created_at: row.create_time ? new Date(row.create_time * 1000).toISOString() : now,
        updated_at: now,
      });
    }

    return {
      manifest: {
        migrationVersion: '1.0.0',
        exportId: `likeshop_import_${Date.now()}`,
        exportedAt: now,
        source: 'LikeShop',
        sourceVersion: '*',
        adapter: 'likeshop-v1.0',
        stats: { products: data.products.length, categories: data.categories.length, users: data.users.length },
      },
      data: { ...data, productSkus: [], productImages: [] },
    };
  }

  _convertFromJson(jsonContent) {
    let source;
    try { source = JSON.parse(jsonContent); } catch (e) { throw new Error('JSON解析失败'); }
    if (source.manifest && source.data) return source;
    
    const now = new Date().toISOString();
    return {
      manifest: {
        migrationVersion: '1.0.0',
        exportId: `likeshop_import_${Date.now()}`,
        exportedAt: now,
        source: 'LikeShop',
        adapter: 'likeshop-v1.0',
        stats: { products: (source.products || []).length, categories: (source.categories || []).length },
      },
      data: {
        products: source.products || [],
        categories: source.categories || [],
        users: source.users || [],
        productSkus: source.productSkus || [],
        productImages: [],
      },
    };
  }

  _parseSqlTables(sql) {
    const tables = {};
    const insertRegex = /INSERT\s+INTO\s+`?(\w+)`?\s*(?:\([^)]*\))?\s*VALUES\s*(.*?)(?:;|$)/gims;
    
    for (const match of sql.matchAll(insertRegex)) {
      const tableName = match[1];
      if (!tables[tableName]) tables[tableName] = [];
      
      const valuesStr = match[2];
      const rowRegex = /\(([^)]+)\)\s*(?:,|$)/g;
      let rowMatch;
      while ((rowMatch = rowRegex.exec(valuesStr)) !== null) {
        const vals = this._parseValues(rowMatch[1]);
        const obj = {};
        const keys = ['id', 'name', 'image', 'price', 'market_price', 'stock', 'sales_actual', 'status', 'category_id', 'weigh', 'create_time'];
        for (let i = 0; i < keys.length && i < vals.length; i++) {
          obj[keys[i]] = vals[i];
        }
        tables[tableName].push(obj);
      }
    }
    return tables;
  }

  _parseValues(str) {
    const values = [];
    let current = '';
    let inString = false;
    let stringChar = '';
    
    for (let i = 0; i < str.length; i++) {
      const ch = str[i];
      if (!inString) {
        if (ch === "'" || ch === '"') { inString = true; stringChar = ch; current += ch; }
        else if (ch === ',') { values.push(current.trim()); current = ''; }
        else { current += ch; }
      } else {
        if (ch === '\\') { current += ch + (str[i + 1] || ''); i++; }
        else if (ch === stringChar) { inString = false; current += ch; }
        else { current += ch; }
      }
    }
    if (current.trim()) values.push(current.trim());
    
    return values.map(v => {
      v = v.trim();
      if ((v.startsWith("'") && v.endsWith("'")) || (v.startsWith('"') && v.endsWith('"'))) {
        return v.slice(1, -1).replace(/\\'/g, "'");
      }
      if (v === 'NULL' || v === '') return null;
      const num = Number(v);
      return isNaN(num) ? v : num;
    });
  }

  getHelp() {
    return `
<h4>从LikeShop导出数据</h4>
<ol>
  <li>登录宝塔面板 → 数据库 → 找到LikeShop数据库</li>
  <li>点击"导出" → 勾选 ls_goods, ls_category, ls_user 表</li>
  <li>下载SQL文件上传即可</li>
</ol>
    `.trim();
  }

  getFieldMap() { return this.productFields; }
}

module.exports = LikeShopAdapter;
