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

const PurchaseBatchModel = {
  async getAll(filters = {}) {
    const db = await getDb();
    let sql = `
      SELECT pb.*, su.name AS created_by_name,
             v.vendor_name,
             (SELECT COUNT(*) FROM purchase_requests WHERE batch_id = pb.batch_id) AS request_count
      FROM purchase_batches pb
      LEFT JOIN sso_users su ON pb.created_by = su.user_id
      LEFT JOIN vendors v ON pb.vendor_id = v.vendor_id
      WHERE 1=1
    `;
    const params = [];
    if (filters.status) { sql += ' AND pb.status = ?'; params.push(filters.status); }
    sql += ' ORDER BY pb.created_at DESC';
    const [rows] = await db.query(sql, params);
    return rows;
  },

  async getById(batchId) {
    const db = await getDb();
    const [rows] = await db.query(`
      SELECT pb.*, su.name AS created_by_name, v.vendor_name
      FROM purchase_batches pb
      LEFT JOIN sso_users su ON pb.created_by = su.user_id
      LEFT JOIN vendors v ON pb.vendor_id = v.vendor_id
      WHERE pb.batch_id = ?
    `, [batchId]);
    return rows[0] || null;
  },

  async create({ batchName, category, vendorId, notes, createdBy }) {
    const db = await getDb();
    const [result] = await db.query(
      `INSERT INTO purchase_batches (batch_name, category, vendor_id, notes, created_by)
       VALUES (?, ?, ?, ?, ?)`,
      [batchName || null, category || null, vendorId || null, notes || null, createdBy]
    );
    return result.insertId;
  },

  async update(batchId, { batchName, category, vendorId, notes }) {
    const db = await getDb();
    await db.query(
      `UPDATE purchase_batches SET batch_name = ?, category = ?, vendor_id = ?, notes = ?
       WHERE batch_id = ? AND status = 'pending'`,
      [batchName || null, category || null, vendorId || null, notes || null, batchId]
    );
    return this.getById(batchId);
  },

  async delete(batchId) {
    const db = await getDb();
    // pending 상태만 삭제 가능
    const [batch] = await db.query('SELECT status FROM purchase_batches WHERE batch_id = ?', [batchId]);
    if (!batch.length || batch[0].status !== 'pending') return false;

    // 포함된 요청 복원
    await db.query(
      `UPDATE purchase_requests SET batch_id = NULL, status = 'pending' WHERE batch_id = ?`,
      [batchId]
    );
    await db.query('DELETE FROM purchase_batches WHERE batch_id = ?', [batchId]);
    return true;
  },

  async markPurchased(batchId, purchasedBy) {
    const db = await getDb();
    await db.query(
      `UPDATE purchase_batches SET status = 'purchased', purchased_at = NOW(), purchased_by = ?
       WHERE batch_id = ? AND status = 'pending'`,
      [purchasedBy, batchId]
    );
  },

  async markReceived(batchId, receivedBy) {
    const db = await getDb();
    await db.query(
      `UPDATE purchase_batches SET status = 'received', received_at = NOW(), received_by = ?
       WHERE batch_id = ? AND status = 'purchased'`,
      [receivedBy, batchId]
    );
  },

  // batch에 요청 추가 (검증: pending이고 다른 batch에 속하지 않음)
  async addRequests(batchId, requestIds) {
    const db = await getDb();
    const [existing] = await db.query(
      `SELECT request_id, batch_id, status FROM purchase_requests WHERE request_id IN (?)`,
      [requestIds]
    );
    const invalid = existing.filter(r => r.status !== 'pending' || r.batch_id !== null);
    if (invalid.length > 0) {
      const ids = invalid.map(r => r.request_id);
      throw new Error(`다음 요청은 추가할 수 없습니다 (이미 그룹 소속이거나 대기 상태가 아님): ${ids.join(', ')}`);
    }

    const PurchaseRequestModel = require('./purchaseRequestModel');
    await PurchaseRequestModel.groupIntoBatch(requestIds, batchId);
  },

  // batch에서 요청 제거
  async removeRequests(batchId, requestIds) {
    const db = await getDb();
    const [batch] = await db.query('SELECT status FROM purchase_batches WHERE batch_id = ?', [batchId]);
    if (!batch.length || batch[0].status !== 'pending') {
      throw new Error('진행중인 그룹에서만 요청을 제거할 수 있습니다.');
    }
    const PurchaseRequestModel = require('./purchaseRequestModel');
    await PurchaseRequestModel.removeFromBatch(requestIds);
  }
};

module.exports = PurchaseBatchModel;
