const UnitOfWork = require('../../database/UnitOfWork');
const PoolRepository = require('../../repositories/pool/poolRepository');
const db = require('../../database/database');

async function createPool({ pool_name, description = null, price = 0.00, subscription_coffee_id = null, pool_type = 'other', is_active = true, created_by = null }) {
  const err = new Error('Manual pool creation is disabled. System supports only: ABO 60, ABO 120, Business, Gigantea, Core.');
  err.status = 400;
  throw err;
}

async function listPools() {
  const uow = new UnitOfWork();
  try {
    console.debug('[PoolService.listPools] start');
    // Ensure connection exists even for read-only
    await uow.start();
    const repo = new PoolRepository(uow);
    const pools = await repo.findAll();
    await uow.commit(); // harmless commit; ensures proper cleanup if UnitOfWork requires it
    console.debug('[PoolService.listPools] success', { count: pools.length });
    return pools;
  } catch (err) {
    console.error('[PoolService.listPools] error', err);
    try { await uow.rollback(); } catch (_) { console.warn('[PoolService.listPools] rollback failed'); }
    throw err;
  }
}

async function updatePoolState(id, is_active, actorUserId) {
  if (typeof is_active !== 'boolean') {
    const err = new Error('is_active must be a boolean');
    err.status = 400;
    throw err;
  }
  const uow = new UnitOfWork();
  try {
    console.debug('[PoolService.updatePoolState] start', { id, is_active });
    await uow.start();
    const repo = new PoolRepository(uow);
    const updated = await repo.updateActive(id, is_active, actorUserId);
    await uow.commit();
    console.debug('[PoolService.updatePoolState] success', { id, is_active });
    return updated;
  } catch (err) {
    console.error('[PoolService.updatePoolState] error', err);
    try { await uow.rollback(); } catch (_) { console.warn('[PoolService.updatePoolState] rollback failed'); }
    throw err;
  }
}

async function updatePoolSubscription({ id, subscription_coffee_id = null, actorUserId = null }) {
  let normalizedSubscriptionCoffeeId = null;
  if (subscription_coffee_id !== null && subscription_coffee_id !== undefined && String(subscription_coffee_id).trim() !== '') {
    const sid = Number(subscription_coffee_id);
    if (!Number.isFinite(sid) || sid <= 0) {
      const err = new Error('Invalid subscription_coffee_id');
      err.status = 400;
      throw err;
    }
    const [rows] = await db.query('SELECT id FROM coffee_table WHERE id = ? LIMIT 1', [sid]);
    if (!rows.length) {
      const err = new Error('Selected subscription not found');
      err.status = 400;
      throw err;
    }
    normalizedSubscriptionCoffeeId = sid;
  }

  const uow = new UnitOfWork();
  try {
    await uow.start();
    const repo = new PoolRepository(uow);
    const updated = await repo.updateSubscriptionLink(id, normalizedSubscriptionCoffeeId, actorUserId);
    await uow.commit();
    return updated;
  } catch (err) {
    try { await uow.rollback(); } catch (_) { console.warn('[PoolService.updatePoolSubscription] rollback failed'); }
    throw err;
  }
}

module.exports = { createPool, listPools, updatePoolState, updatePoolSubscription };