// models/pageAccessModel.js
const db = require('../db/connection');

const PageAccessModel = {
  // 사용자의 페이지 권한 조회
  getUserPageAccess: (userId, callback) => {
    const sql = `
      SELECT
        p.id,
        p.page_key,
        p.page_name,
        p.page_path,
        p.category,
        p.is_admin_only,
        COALESCE(upa.can_access, p.is_default_accessible, 0) as can_access,
        upa.granted_at,
        upa.granted_by,
        granter.username as granted_by_username
      FROM pages p
      LEFT JOIN user_page_access upa ON p.id = upa.page_id AND upa.user_id = ?
      LEFT JOIN users granter ON upa.granted_by = granter.user_id
      ORDER BY p.category, p.display_order
    `;

    db.query(sql, [userId], callback);
  },

  // 모든 페이지 목록 조회
  getAllPages: (callback) => {
    const sql = `
      SELECT
        id,
        page_key,
        page_name,
        page_path,
        category,
        description,
        is_admin_only,
        display_order
      FROM pages
      ORDER BY category, display_order
    `;

    db.query(sql, callback);
  },

  // 페이지 권한 부여
  grantPageAccess: (userId, pageId, grantedBy, callback) => {
    const sql = `
      INSERT INTO user_page_access (user_id, page_id, can_access, granted_by, granted_at)
      VALUES (?, ?, 1, ?, NOW())
      ON DUPLICATE KEY UPDATE
        can_access = 1,
        granted_by = ?,
        granted_at = NOW()
    `;

    db.query(sql, [userId, pageId, grantedBy, grantedBy], callback);
  },

  // 페이지 권한 회수
  revokePageAccess: (userId, pageId, callback) => {
    const sql = `
      DELETE FROM user_page_access
      WHERE user_id = ? AND page_id = ?
    `;

    db.query(sql, [userId, pageId], callback);
  },

  // 여러 페이지 권한 일괄 설정
  setUserPageAccess: (userId, pageIds, grantedBy, callback) => {
    db.beginTransaction((err) => {
      if (err) return callback(err);

      // 기존 권한 모두 삭제
      const deleteSql = 'DELETE FROM user_page_access WHERE user_id = ?';

      db.query(deleteSql, [userId], (err) => {
        if (err) {
          return db.rollback(() => callback(err));
        }

        // 새 권한이 없으면 커밋하고 종료
        if (!pageIds || pageIds.length === 0) {
          return db.commit((err) => {
            if (err) return db.rollback(() => callback(err));
            callback(null, { affectedRows: 0 });
          });
        }

        // 새 권한 추가
        const values = pageIds.map(pageId => [userId, pageId, 1, grantedBy]);
        const insertSql = `
          INSERT INTO user_page_access (user_id, page_id, can_access, granted_by, granted_at)
          VALUES ?
        `;

        db.query(insertSql, [values], (err, result) => {
          if (err) {
            return db.rollback(() => callback(err));
          }

          db.commit((err) => {
            if (err) return db.rollback(() => callback(err));
            callback(null, result);
          });
        });
      });
    });
  },

  // 특정 페이지 접근 권한 확인
  checkPageAccess: (userId, pageKey, callback) => {
    const sql = `
      SELECT
        COALESCE(upa.can_access, p.is_default_accessible, 0) as can_access,
        p.is_admin_only
      FROM pages p
      LEFT JOIN user_page_access upa ON p.id = upa.page_id AND upa.user_id = ?
      WHERE p.page_key = ?
    `;

    db.query(sql, [userId, pageKey], (err, results) => {
      if (err) return callback(err);
      if (results.length === 0) return callback(null, { can_access: false });
      callback(null, results[0]);
    });
  },

  // 계정이 있는 작업자 목록 조회 (권한 관리용)
  getUsersWithAccounts: (callback) => {
    const sql = `
      SELECT
        u.user_id,
        u.username,
        u.name,
        u.role_id,
        r.name as role_name,
        u.user_id as worker_user_id,
        w.worker_name,
        w.job_type,
        COUNT(upa.page_id) as granted_pages_count
      FROM users u
      LEFT JOIN roles r ON u.role_id = r.id
      LEFT JOIN workers w ON u.user_id = w.user_id
      LEFT JOIN user_page_access upa ON u.user_id = upa.user_id AND upa.can_access = 1
      WHERE u.is_active = 1
        AND u.role_id IN (4, 5)
      GROUP BY u.user_id
      ORDER BY w.worker_name, u.username
    `;

    db.query(sql, callback);
  }
};

module.exports = PageAccessModel;
