const sqlite3 = require('sqlite3').verbose();
const path = require('path');
const fs = require('fs');

// 确保数据库目录存在
const dbDir = path.dirname(process.env.DB_PATH || './database/xlxumu_dev.db');
if (!fs.existsSync(dbDir)) {
  fs.mkdirSync(dbDir, { recursive: true });
}

const dbPath = process.env.DB_PATH || './database/xlxumu_dev.db';

// 创建数据库连接
const db = new sqlite3.Database(dbPath, (err) => {
  if (err) {
    console.error('❌ SQLite数据库连接失败:', err.message);
  } else {
    console.log('✅ SQLite数据库连接成功:', dbPath);
  }
});

// 初始化数据库表结构
const initDatabase = () => {
  return new Promise((resolve, reject) => {
    // 用户表
    db.run(`
      CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username VARCHAR(50) UNIQUE NOT NULL,
        email VARCHAR(100) UNIQUE,
        phone VARCHAR(20),
        password_hash VARCHAR(255) NOT NULL,
        real_name VARCHAR(50),
        user_type TEXT CHECK(user_type IN ('admin', 'farmer', 'government', 'bank', 'insurance')) DEFAULT 'farmer',
        status TEXT CHECK(status IN ('active', 'inactive', 'suspended')) DEFAULT 'active',
        avatar_url VARCHAR(255),
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `, (err) => {
      if (err) {
        console.error('创建用户表失败:', err.message);
        reject(err);
        return;
      }
    });

    // 角色表
    db.run(`
      CREATE TABLE IF NOT EXISTS roles (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name VARCHAR(50) UNIQUE NOT NULL,
        description TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `, (err) => {
      if (err) {
        console.error('创建角色表失败:', err.message);
        reject(err);
        return;
      }
    });

    // 权限表
    db.run(`
      CREATE TABLE IF NOT EXISTS permissions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name VARCHAR(50) UNIQUE NOT NULL,
        description TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `, (err) => {
      if (err) {
        console.error('创建权限表失败:', err.message);
        reject(err);
        return;
      }
    });

    // 用户角色关联表
    db.run(`
      CREATE TABLE IF NOT EXISTS user_roles (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id INTEGER NOT NULL,
        role_id INTEGER NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id),
        FOREIGN KEY (role_id) REFERENCES roles(id)
      )
    `, (err) => {
      if (err) {
        console.error('创建用户角色表失败:', err.message);
        reject(err);
        return;
      }
    });

    // 角色权限关联表
    db.run(`
      CREATE TABLE IF NOT EXISTS role_permissions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        role_id INTEGER NOT NULL,
        permission_id INTEGER NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (role_id) REFERENCES roles(id),
        FOREIGN KEY (permission_id) REFERENCES permissions(id)
      )
    `, (err) => {
      if (err) {
        console.error('创建角色权限表失败:', err.message);
        reject(err);
        return;
      }
    });

    // 牛只档案表
    db.run(`
      CREATE TABLE IF NOT EXISTS cattle (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        ear_tag VARCHAR(50) UNIQUE NOT NULL,
        name VARCHAR(100),
        breed VARCHAR(100),
        gender TEXT CHECK(gender IN ('male', 'female')) NOT NULL,
        birth_date DATE,
        color VARCHAR(50),
        weight DECIMAL(8,2),
        health_status TEXT CHECK(health_status IN ('healthy', 'sick', 'quarantine', 'deceased')) DEFAULT 'healthy',
        status TEXT CHECK(status IN ('active', 'sold', 'deceased', 'transferred')) DEFAULT 'active',
        owner_id INTEGER,
        farm_location VARCHAR(255),
        notes TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (owner_id) REFERENCES users(id)
      )
    `, (err) => {
      if (err) {
        console.error('创建牛只档案表失败:', err.message);
        reject(err);
        return;
      }
    });

    console.log('✅ 数据库表结构初始化完成');
    resolve();
  });
};

// 插入初始数据
const insertInitialData = async () => {
  return new Promise((resolve, reject) => {
    // 等待所有表创建完成后再插入数据
    setTimeout(() => {
      // 插入默认角色
      const roles = [
        { name: 'admin', description: '系统管理员' },
        { name: 'farmer', description: '养殖户' },
        { name: 'government', description: '政府监管员' },
        { name: 'bank', description: '银行工作人员' },
        { name: 'insurance', description: '保险公司工作人员' }
      ];

      const permissions = [
        { name: 'user_manage', description: '用户管理' },
        { name: 'cattle_manage', description: '牛只管理' },
        { name: 'finance_manage', description: '金融管理' },
        { name: 'loan_manage', description: '贷款管理' },
        { name: 'insurance_manage', description: '保险管理' },
        { name: 'data_view', description: '数据查看' },
        { name: 'report_generate', description: '报告生成' }
      ];

      // 插入角色
      const insertRole = db.prepare('INSERT OR IGNORE INTO roles (name, description) VALUES (?, ?)');
      roles.forEach(role => {
        insertRole.run(role.name, role.description);
      });
      insertRole.finalize();

      // 插入权限
      const insertPermission = db.prepare('INSERT OR IGNORE INTO permissions (name, description) VALUES (?, ?)');
      permissions.forEach(permission => {
        insertPermission.run(permission.name, permission.description);
      });
      insertPermission.finalize();

      console.log('✅ 初始数据插入完成');
      resolve();
    }, 100); // 延迟100ms确保表创建完成
  });
};

// 模拟MySQL连接池接口
const pool = {
  execute: (sql, params = []) => {
    return new Promise((resolve, reject) => {
      db.all(sql, params, (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve([rows]);
        }
      });
    });
  },
  
  getConnection: () => {
    return Promise.resolve({
      execute: pool.execute,
      release: () => {}
    });
  }
};

// 测试数据库连接
const testDatabaseConnection = async () => {
  try {
    await initDatabase();
    await insertInitialData();
    console.log('✅ SQLite数据库初始化完成');
    return true;
  } catch (error) {
    console.error('❌ SQLite数据库初始化失败:', error.message);
    return false;
  }
};

module.exports = {
  pool,
  testDatabaseConnection,
  db
};