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

const PurchaseModel = {
  // 구매 내역 목록
  async getAll(filters = {}) {
    const db = await getDb();
    let sql = `
      SELECT p.*, ci.item_name, ci.spec, ci.maker, ci.category, ci.unit, ci.photo_path,
             v.vendor_name, su.name AS purchaser_name
      FROM purchases p
      JOIN consumable_items ci ON p.item_id = ci.item_id
      LEFT JOIN vendors v ON p.vendor_id = v.vendor_id
      LEFT JOIN sso_users su ON p.purchaser_id = su.user_id
      WHERE 1=1
    `;
    const params = [];

    if (filters.vendor_id) { sql += ' AND p.vendor_id = ?'; params.push(filters.vendor_id); }
    if (filters.category) { sql += ' AND ci.category = ?'; params.push(filters.category); }
    if (filters.from_date) { sql += ' AND p.purchase_date >= ?'; params.push(filters.from_date); }
    if (filters.to_date) { sql += ' AND p.purchase_date <= ?'; params.push(filters.to_date); }
    if (filters.year_month) {
      sql += ' AND DATE_FORMAT(p.purchase_date, "%Y-%m") = ?';
      params.push(filters.year_month);
    }

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

  // 구매 처리 (구매신청 → 구매 내역 생성 + 상태 변경)
  async createFromRequest(data) {
    const db = await getDb();

    // 구매 내역 INSERT
    const [result] = await db.query(
      `INSERT INTO purchases (request_id, item_id, vendor_id, quantity, unit_price, purchase_date, purchaser_id, notes)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
      [data.request_id || null, data.item_id, data.vendor_id || null,
       data.quantity, data.unit_price, data.purchase_date, data.purchaser_id, data.notes || null]
    );

    // 구매신청 상태 → purchased
    if (data.request_id) {
      await db.query(
        `UPDATE purchase_requests SET status = 'purchased' WHERE request_id = ?`,
        [data.request_id]
      );
    }

    return result.insertId;
  },

  // 기준가 업데이트 + 이력 기록
  async updateBasePrice(itemId, newPrice, oldPrice, changedBy) {
    const db = await getDb();

    // 이력 기록
    await db.query(
      `INSERT INTO consumable_price_history (item_id, old_price, new_price, changed_by)
       VALUES (?, ?, ?, ?)`,
      [itemId, oldPrice, newPrice, changedBy]
    );

    // base_price 갱신
    await db.query(
      `UPDATE consumable_items SET base_price = ? WHERE item_id = ?`,
      [newPrice, itemId]
    );
  },

  // 설비 자동 등록 시도 (category='equipment')
  async tryAutoRegisterEquipment(purchaseData) {
    try {
      const EquipmentModel = require('./equipmentModel');
      const equipmentCode = await EquipmentModel.getNextEquipmentCode('TKP');

      await EquipmentModel.create({
        equipment_code: equipmentCode,
        equipment_name: purchaseData.item_name,
        manufacturer: purchaseData.maker || null,
        supplier: purchaseData.vendor_name || null,
        purchase_price: purchaseData.unit_price,
        installation_date: purchaseData.purchase_date,
        status: 'active',
        notes: `구매 자동 등록 (purchase_id: ${purchaseData.purchase_id})`
      });

      return { success: true, equipment_code: equipmentCode };
    } catch (err) {
      console.error('[purchase] 설비 자동 등록 실패:', err.message);

      // fire-and-forget: admin 알림 전송
      const notifyHelper = require('../shared/utils/notifyHelper');
      notifyHelper.send({
        type: 'equipment',
        title: `설비 자동 등록 실패: ${purchaseData.item_name}`,
        message: `구매 완료 후 설비 자동 등록에 실패했습니다. 수동으로 등록해주세요. 오류: ${err.message}`,
        link_url: '/pages/admin/equipments.html',
        created_by: purchaseData.purchaser_id
      }).catch(() => {});

      return { success: false, error: err.message };
    }
  },

  // 업체 목록 (vendors 테이블 직접 조회)
  async getVendors() {
    const db = await getDb();
    const [rows] = await db.query(
      'SELECT vendor_id, vendor_name FROM vendors WHERE is_active = 1 ORDER BY vendor_name'
    );
    return rows;
  },

  // 소모품 목록 (구매신청용)
  async getConsumableItems(activeOnly = true) {
    const db = await getDb();
    let sql = 'SELECT item_id, item_name, spec, maker, category, base_price, unit, photo_path FROM consumable_items';
    if (activeOnly) sql += ' WHERE is_active = 1';
    sql += ' ORDER BY category, item_name';
    const [rows] = await db.query(sql);
    return rows;
  },

  // 미등록 품목 → 소모품 마스터 등록
  async registerToMaster(customItemName, customCategory, maker) {
    const db = await getDb();

    // 중복 확인
    const [existing] = await db.query(
      `SELECT item_id FROM consumable_items WHERE item_name = ? AND (maker = ? OR (maker IS NULL AND ? IS NULL))`,
      [customItemName, maker || null, maker || null]
    );
    if (existing.length > 0) {
      return existing[0].item_id;
    }

    // 신규 등록 (photo_path = NULL)
    const [result] = await db.query(
      `INSERT INTO consumable_items (item_name, maker, category, is_active) VALUES (?, ?, ?, 1)`,
      [customItemName, maker || null, customCategory || 'consumable']
    );
    return result.insertId;
  },

  // 가격 변동 이력
  async getPriceHistory(itemId) {
    const db = await getDb();
    const [rows] = await db.query(
      `SELECT cph.*, su.name AS changed_by_name
       FROM consumable_price_history cph
       LEFT JOIN sso_users su ON cph.changed_by = su.user_id
       WHERE cph.item_id = ?
       ORDER BY cph.changed_at DESC`,
      [itemId]
    );
    return rows;
  }
};

module.exports = PurchaseModel;
