import { createClient } from '@larksuiteoapi/node-sdk';

const client = createClient({
  baseURL: 'https://open.feishu.cn',
  accessToken: process.env.FEISHU_USER_ACCESS_TOKEN,
});

async function createBitable() {
  try {
    // Step 1: Create the app
    console.log('Creating app...');
    const appRes = await client.bitable.app.create({
      data: { name: '库存清单' }
    });
    
    if (appRes.code !== 0) {
      throw new Error(`Failed to create app: ${JSON.stringify(appRes)}`);
    }
    
    const appToken = appRes.data.app.app_token;
    console.log('App created:', appToken);
    
    // Step 2: Get the default table
    console.log('Getting tables...');
    const tablesRes = await client.bitable.appTable.list({
      path: { app_token: appToken }
    });
    
    if (tablesRes.code !== 0) {
      throw new Error(`Failed to list tables: ${JSON.stringify(tablesRes)}`);
    }
    
    const tableId = tablesRes.data.items[0].table_id;
    console.log('Table ID:', tableId);
    
    // Step 3: Create fields (日期，规格，数量)
    console.log('Creating fields...');
    
    // Date field
    const dateFieldRes = await client.bitable.appTableField.create({
      path: { app_token: appToken, table_id: tableId },
      data: {
        field_name: '日期',
        type: 5, // DateTime
      }
    });
    
    // Spec field (Single line text)
    const specFieldRes = await client.bitable.appTableField.create({
      path: { app_token: appToken, table_id: tableId },
      data: {
        field_name: '规格',
        type: 1, // Text
      }
    });
    
    // Quantity field (Number)
    const qtyFieldRes = await client.bitable.appTableField.create({
      path: { app_token: appToken, table_id: tableId },
      data: {
        field_name: '数量',
        type: 2, // Number
      }
    });
    
    console.log('Fields created');
    
    // Step 4: Delete default empty rows first
    console.log('Cleaning empty rows...');
    const recordsRes = await client.bitable.appTableRecord.list({
      path: { app_token: appToken, table_id: tableId }
    });
    
    if (recordsRes.code === 0 && recordsRes.data.items.length > 0) {
      const recordIds = recordsRes.data.items.map(r => r.record_id);
      await client.bitable.appTableRecord.batchDelete({
        path: { app_token: appToken, table_id: tableId },
        data: { record_ids: recordIds }
      });
      console.log('Deleted', recordIds.length, 'empty rows');
    }
    
    // Step 5: Add 5 rows of sample data
    console.log('Adding sample data...');
    const now = Date.now();
    const sampleData = [
      { '日期': now, '规格': '规格 A-001', '数量': 100 },
      { '日期': now - 86400000, '规格': '规格 B-002', '数量': 250 },
      { '日期': now - 172800000, '规格': '规格 C-003', '数量': 75 },
      { '日期': now - 259200000, '规格': '规格 D-004', '数量': 500 },
      { '日期': now - 345600000, '规格': '规格 E-005', '数量': 150 },
    ];
    
    const batchRes = await client.bitable.appTableRecord.batchCreate({
      path: { app_token: appToken, table_id: tableId },
      data: {
        records: sampleData.map(fields => ({ fields }))
      }
    });
    
    if (batchRes.code !== 0) {
      throw new Error(`Failed to create records: ${JSON.stringify(batchRes)}`);
    }
    
    console.log('Created', batchRes.data.items.length, 'records');
    
    // Step 6: Return the link
    const link = `https://feishu.cn/bitables/${appToken}`;
    console.log('\n✅ 库存清单创建完成!');
    console.log('表格链接:', link);
    
    return { success: true, appToken, link };
    
  } catch (error) {
    console.error('Error:', error.message);
    return { success: false, error: error.message };
  }
}

createBitable();
