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

const SettlementModel = {
  // 월간 분류별 요약
  async getCategorySummary(yearMonth) {
    const db = await getDb();
    const [rows] = await db.query(`
      SELECT ci.category,
             COUNT(*) AS count,
             SUM(p.quantity * p.unit_price) AS total_amount
      FROM purchases p
      JOIN consumable_items ci ON p.item_id = ci.item_id
      WHERE DATE_FORMAT(p.purchase_date, '%Y-%m') = ?
      GROUP BY ci.category
    `, [yearMonth]);
    return rows;
  },

  // 월간 업체별 요약
  async getVendorSummary(yearMonth) {
    const db = await getDb();
    const [rows] = await db.query(`
      SELECT v.vendor_id, v.vendor_name,
             COUNT(*) AS count,
             SUM(p.quantity * p.unit_price) AS total_amount,
             ms.settlement_id, ms.status AS settlement_status,
             ms.completed_at, ms.notes AS settlement_notes
      FROM purchases p
      LEFT JOIN vendors v ON p.vendor_id = v.vendor_id
      LEFT JOIN monthly_settlements ms ON ms.vendor_id = p.vendor_id AND ms.year_month = ?
      WHERE DATE_FORMAT(p.purchase_date, '%Y-%m') = ?
      GROUP BY COALESCE(v.vendor_id, 0), v.vendor_name, ms.settlement_id, ms.status, ms.completed_at, ms.notes
      ORDER BY total_amount DESC
    `, [yearMonth, yearMonth]);
    return rows;
  },

  // 월간 상세 구매 목록
  async getMonthlyPurchases(yearMonth) {
    const db = await getDb();
    const [rows] = await db.query(`
      SELECT p.*, ci.item_name, ci.spec, ci.maker, ci.category, ci.unit, ci.base_price, 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 DATE_FORMAT(p.purchase_date, '%Y-%m') = ?
      ORDER BY p.purchase_date DESC
    `, [yearMonth]);
    return rows;
  },

  // 정산 완료 처리
  async completeSettlement(yearMonth, vendorId, completedBy, notes) {
    const db = await getDb();

    // 총액 계산
    const [[{ total }]] = await db.query(`
      SELECT COALESCE(SUM(p.quantity * p.unit_price), 0) AS total
      FROM purchases p
      WHERE p.vendor_id = ? AND DATE_FORMAT(p.purchase_date, '%Y-%m') = ?
    `, [vendorId, yearMonth]);

    // UPSERT
    await db.query(`
      INSERT INTO monthly_settlements (year_month, vendor_id, total_amount, status, completed_at, completed_by, notes)
      VALUES (?, ?, ?, 'completed', NOW(), ?, ?)
      ON DUPLICATE KEY UPDATE status = 'completed', total_amount = ?, completed_at = NOW(), completed_by = ?, notes = ?
    `, [yearMonth, vendorId, total, completedBy, notes || null, total, completedBy, notes || null]);

    return { year_month: yearMonth, vendor_id: vendorId, total_amount: total, status: 'completed' };
  },

  // 정산 취소
  async cancelSettlement(yearMonth, vendorId) {
    const db = await getDb();
    await db.query(`
      UPDATE monthly_settlements SET status = 'pending', completed_at = NULL, completed_by = NULL
      WHERE year_month = ? AND vendor_id = ?
    `, [yearMonth, vendorId]);
    return { year_month: yearMonth, vendor_id: vendorId, status: 'pending' };
  },

  // 가격 변동 목록 (월간)
  async getPriceChanges(yearMonth) {
    const db = await getDb();
    const [rows] = await db.query(`
      SELECT p.purchase_id, p.purchase_date, p.unit_price, p.quantity,
             ci.item_id, ci.item_name, ci.spec, ci.maker, ci.category, ci.base_price,
             v.vendor_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
      WHERE DATE_FORMAT(p.purchase_date, '%Y-%m') = ?
        AND p.unit_price != ci.base_price
      ORDER BY ABS(p.unit_price - ci.base_price) DESC
    `, [yearMonth]);
    return rows;
  }
};

module.exports = SettlementModel;
