import { getDb } from './db.js';

// All time windows are computed in local time using SQLite's `datetime('now', 'localtime')`.
// Cost of goods (COG) and profit are computed against each part's current cost_price —
// the schema does not snapshot cost at sale time, so historical cost changes are not
// reflected. Custom (non-inventory) lines contribute to sale revenue but have zero COG.

const COG_SUBQUERY = `
  COALESCE((
    SELECT SUM(l.quantity * p.cost_price)
    FROM invoice_lines l
    JOIN parts p ON p.id = l.part_id
    WHERE l.invoice_id = invoices.id AND l.affects_inventory = 1
  ), 0)
`;

function windowStats(dateClause) {
  return getDb().prepare(`
    SELECT
      COUNT(*) AS invoice_count,
      COALESCE(SUM(total_dirams), 0) AS sale_dirams,
      COALESCE(SUM(${COG_SUBQUERY}), 0) AS cog_dirams,
      COALESCE(SUM(total_dirams - ${COG_SUBQUERY}), 0) AS profit_dirams
    FROM invoices
    WHERE status = 'saved'${dateClause ? ' AND ' + dateClause : ''}
  `).get();
}

export function salesSummary() {
  return {
    all_time: windowStats(''),
    today: windowStats(`date(saved_at, 'localtime') = date('now', 'localtime')`),
    week: windowStats(`date(saved_at, 'localtime') >= date('now', 'localtime', '-6 days')`),
    month: windowStats(`strftime('%Y-%m', saved_at, 'localtime') = strftime('%Y-%m', 'now', 'localtime')`)
  };
}

export function topSellingParts(limit = 10) {
  return getDb().prepare(`
    SELECT
      p.id, p.sku, p.name_en, p.name_tg,
      SUM(l.quantity) AS units_sold,
      SUM(l.quantity * l.unit_price_dirams) AS sale_dirams,
      SUM(l.quantity * p.cost_price) AS cog_dirams,
      SUM(l.quantity * (l.unit_price_dirams - p.cost_price)) AS profit_dirams
    FROM invoice_lines l
    JOIN invoices i ON i.id = l.invoice_id
    JOIN parts p    ON p.id = l.part_id
    WHERE i.status = 'saved' AND l.affects_inventory = 1
    GROUP BY p.id
    ORDER BY profit_dirams DESC, units_sold DESC
    LIMIT ?
  `).all(limit);
}

export function inventorySummary() {
  const db = getDb();
  const all = db.prepare(`
    SELECT
      COUNT(*) AS sku_count,
      COALESCE(SUM(quantity_on_hand), 0) AS units_on_hand,
      COALESCE(SUM(quantity_on_hand * cost_price), 0) AS cost_value_dirams,
      COALESCE(SUM(quantity_on_hand * sale_price), 0) AS sale_value_dirams
    FROM parts WHERE active = 1
  `).get();

  const lowStockCount = db.prepare(`
    SELECT COUNT(*) AS n FROM parts
    WHERE active = 1 AND quantity_on_hand <= reorder_level
  `).get().n;

  const outOfStockCount = db.prepare(`
    SELECT COUNT(*) AS n FROM parts
    WHERE active = 1 AND quantity_on_hand <= 0
  `).get().n;

  return { ...all, lowStockCount, outOfStockCount };
}

export function recentSales(limit = 10) {
  return getDb().prepare(`
    SELECT
      id,
      total_dirams AS sale_dirams,
      ${COG_SUBQUERY} AS cog_dirams,
      total_dirams - ${COG_SUBQUERY} AS profit_dirams,
      saved_at,
      (SELECT COUNT(*) FROM invoice_lines WHERE invoice_id = invoices.id) AS line_count
    FROM invoices
    WHERE status = 'saved'
    ORDER BY saved_at DESC, id DESC
    LIMIT ?
  `).all(limit);
}
