// models/purchaseRequestModel.js
const { getDb } = require('../dbPool');

const PurchaseRequestModel = {
  // 구매신청 목록 (소모품 정보 LEFT JOIN — item_id NULL 허용)
  async getAll(filters = {}) {
    const db = await getDb();
    let sql = `
      SELECT pr.*, ci.item_name, ci.spec, ci.maker, ci.category, ci.base_price, ci.unit,
             ci.photo_path AS ci_photo_path, pr.photo_path AS pr_photo_path,
             pr.custom_item_name, pr.custom_category,
             su.name AS requester_name
      FROM purchase_requests pr
      LEFT JOIN consumable_items ci ON pr.item_id = ci.item_id
      LEFT JOIN sso_users su ON pr.requester_id = su.user_id
      WHERE 1=1
    `;
    const params = [];

    if (filters.status) { sql += ' AND pr.status = ?'; params.push(filters.status); }
    if (filters.requester_id) { sql += ' AND pr.requester_id = ?'; params.push(filters.requester_id); }
    if (filters.category) {
      sql += ' AND (ci.category = ? OR pr.custom_category = ?)';
      params.push(filters.category, filters.category);
    }
    if (filters.from_date) { sql += ' AND pr.request_date >= ?'; params.push(filters.from_date); }
    if (filters.to_date) { sql += ' AND pr.request_date <= ?'; params.push(filters.to_date); }

    sql += ' ORDER BY pr.created_at DESC';
    const [rows] = await db.query(sql, params);
    return rows;
  },

  // 단건 조회
  async getById(requestId) {
    const db = await getDb();
    const [rows] = await db.query(`
      SELECT pr.*, ci.item_name, ci.spec, ci.maker, ci.category, ci.base_price, ci.unit,
             ci.photo_path AS ci_photo_path, pr.photo_path AS pr_photo_path,
             pr.custom_item_name, pr.custom_category,
             su.name AS requester_name
      FROM purchase_requests pr
      LEFT JOIN consumable_items ci ON pr.item_id = ci.item_id
      LEFT JOIN sso_users su ON pr.requester_id = su.user_id
      WHERE pr.request_id = ?
    `, [requestId]);
    return rows[0] || null;
  },

  // 구매신청 생성
  async create(data) {
    const db = await getDb();
    const [result] = await db.query(
      `INSERT INTO purchase_requests (item_id, custom_item_name, custom_category, quantity, requester_id, request_date, notes, photo_path)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
      [data.item_id || null, data.custom_item_name || null, data.custom_category || null,
       data.quantity || 1, data.requester_id, data.request_date, data.notes || null, data.photo_path || null]
    );
    return this.getById(result.insertId);
  },

  // 상태 변경 (보류)
  async hold(requestId, holdReason) {
    const db = await getDb();
    await db.query(
      `UPDATE purchase_requests SET status = 'hold', hold_reason = ? WHERE request_id = ?`,
      [holdReason || null, requestId]
    );
    return this.getById(requestId);
  },

  // 상태 → purchased
  async markPurchased(requestId) {
    const db = await getDb();
    await db.query(
      `UPDATE purchase_requests SET status = 'purchased' WHERE request_id = ?`,
      [requestId]
    );
  },

  // pending으로 되돌리기
  async revertToPending(requestId) {
    const db = await getDb();
    await db.query(
      `UPDATE purchase_requests SET status = 'pending', hold_reason = NULL WHERE request_id = ?`,
      [requestId]
    );
    return this.getById(requestId);
  },

  // item_id 업데이트 (마스터 등록 후)
  async updateItemId(requestId, itemId) {
    const db = await getDb();
    await db.query(
      `UPDATE purchase_requests SET item_id = ? WHERE request_id = ?`,
      [itemId, requestId]
    );
  },

  // 삭제 (admin only, pending 상태만)
  async delete(requestId) {
    const db = await getDb();
    const [result] = await db.query(
      `DELETE FROM purchase_requests WHERE request_id = ? AND status = 'pending'`,
      [requestId]
    );
    return result.affectedRows > 0;
  }
};

module.exports = PurchaseRequestModel;
