const pool = require('../../database/database');

class CoffeeShippingFeeService {
  static _normalizePieceCount(value) {
    const n = Number(value);
    if (!Number.isInteger(n)) return null;
    if (![60, 120].includes(n)) return null;
    return n;
  }

  static _normalizePrice(value) {
    const n = Number(value);
    if (!Number.isFinite(n)) return null;
    if (n < 0) return null;
    return n;
  }

  static _mapRow(row) {
    if (!row) return null;
    return {
      pieceCount: Number(row.piece_count),
      price: Number(row.price),
    };
  }

  static async list() {
    const [rows] = await pool.query(
      'SELECT piece_count, price FROM coffee_shipping_fees ORDER BY piece_count ASC'
    );
    return (rows || []).map((r) => this._mapRow(r));
  }

  static async get(pieceCount) {
    const pc = this._normalizePieceCount(pieceCount);
    if (!pc) return null;

    const [rows] = await pool.query(
      'SELECT piece_count, price FROM coffee_shipping_fees WHERE piece_count = ? LIMIT 1',
      [pc]
    );
    return this._mapRow(rows?.[0]);
  }

  static async setPrice(pieceCount, price) {
    const pc = this._normalizePieceCount(pieceCount);
    if (!pc) {
      const err = new Error('pieceCount must be 60 or 120');
      err.status = 400;
      throw err;
    }

    const p = this._normalizePrice(price);
    if (p === null) {
      const err = new Error('price must be a number >= 0');
      err.status = 400;
      throw err;
    }

    await pool.query(
      `INSERT INTO coffee_shipping_fees (piece_count, price)
       VALUES (?, ?)
       ON DUPLICATE KEY UPDATE price = VALUES(price)`,
      [pc, p]
    );

    return this.get(pc);
  }
}

module.exports = CoffeeShippingFeeService;
