import knex from 'knex';

// 数据库配置
const dbConfig = {
  client: 'mysql2',
  connection: {
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT || '3306'),
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || 'password',
    database: process.env.DB_NAME || 'crawlful_hub',
    charset: 'utf8mb4',
    multipleStatements: true
  },
  pool: {
    min: 5,
    max: 20,
    acquireTimeoutMillis: 30000,
    idleTimeoutMillis: 60000
  },
  migrations: {
    directory: './src/config/migrations'
  },
  seeds: {
    directory: './src/config/seeds'
  },
  acquireConnectionTimeout: 30000
};

// 创建数据库连接
const db = knex(dbConfig);

// 初始化数据库
export const initializeDatabase = async () => {
  try {
    // 测试连接
    await db.raw('SELECT 1');
    
    // 检查并创建表
    await createTables();
    
    return db;
  } catch (error) {
    console.error('数据库初始化失败:', error);
    throw error;
  }
};

// 创建表
const createTables = async () => {
  // 商品表
  if (!(await db.schema.hasTable('cf_product'))) {
    await db.schema.createTable('cf_product', (table) => {
      table.string('id').primary();
      table.string('tenant_id').notNullable();
      table.string('shop_id').notNullable();
      table.string('platform').notNullable();
      table.string('product_id').notNullable();
      table.string('name').notNullable();
      table.decimal('price', 10, 2).notNullable();
      table.string('status').notNullable();
      table.json('images').nullable();
      table.json('skus').nullable();
      table.json('attributes').nullable();
      table.timestamp('created_at').defaultTo(db.fn.now());
      table.timestamp('updated_at').defaultTo(db.fn.now());
      
      // 唯一约束
      table.unique(['platform', 'product_id']);
    });
  }
  
  // 订单表
  if (!(await db.schema.hasTable('cf_order'))) {
    await db.schema.createTable('cf_order', (table) => {
      table.string('id').primary();
      table.string('tenant_id').notNullable();
      table.string('shop_id').notNullable();
      table.string('platform').notNullable();
      table.string('order_id').notNullable();
      table.decimal('total_amount', 10, 2).notNullable();
      table.string('status').notNullable();
      table.json('items').nullable();
      table.json('shipping_address').nullable();
      table.timestamp('created_at').defaultTo(db.fn.now());
      table.timestamp('updated_at').defaultTo(db.fn.now());
    });
  }
  
  // 库存表
  if (!(await db.schema.hasTable('cf_inventory'))) {
    await db.schema.createTable('cf_inventory', (table) => {
      table.string('id').primary();
      table.string('tenant_id').notNullable();
      table.string('shop_id').notNullable();
      table.string('product_id').notNullable();
      table.integer('quantity').notNullable();
      table.string('location').nullable();
      table.timestamp('created_at').defaultTo(db.fn.now());
      table.timestamp('updated_at').defaultTo(db.fn.now());
    });
  }
  
  // 用户表
  if (!(await db.schema.hasTable('cf_user'))) {
    await db.schema.createTable('cf_user', (table) => {
      table.string('id').primary();
      table.string('tenant_id').notNullable();
      table.string('username').notNullable();
      table.string('password').notNullable();
      table.string('role').notNullable();
      table.string('email').nullable();
      table.timestamp('created_at').defaultTo(db.fn.now());
      table.timestamp('updated_at').defaultTo(db.fn.now());
    });
  }
  
  // 主权授信池表
  if (!(await db.schema.hasTable('cf_sov_credit_pool'))) {
    await db.schema.createTable('cf_sov_credit_pool', (table) => {
      table.string('id').primary();
      table.string('tenant_id').notNullable();
      table.decimal('max_credit_limit', 15, 2).notNullable();
      table.decimal('available_credit', 15, 2).notNullable();
      table.decimal('reputation_multiplier', 5, 2).notNullable();
      table.string('status').notNullable();
      table.timestamp('created_at').defaultTo(db.fn.now());
      table.timestamp('updated_at').defaultTo(db.fn.now());
      
      // 唯一约束
      table.unique(['tenant_id']);
    });
  }
};

export default db;