const { createPool, listPools, updatePoolState, updatePoolSubscription } = require('../../services/pool/PoolService');
const PoolMemberService = require('../../services/pool/PoolMemberService');
const PoolInflowService = require('../../services/pool/PoolInflowService');

module.exports = {
  async create(req, res) {
    try {
      const { pool_name, description, price, price_net, subscription_coffee_id, pool_type, is_active } = req.body || {};
      const normalizedNetPrice = Number(price_net ?? price);
      const actorUserId = req.user && req.user.userId;
      if (!pool_name) return res.status(400).json({ success: false, message: 'Pool name is required' });
      if (!Number.isFinite(normalizedNetPrice) || normalizedNetPrice < 0) {
        return res.status(400).json({ success: false, message: 'Valid net price per capsule is required' });
      }
      if (pool_type && !['coffee', 'other'].includes(pool_type)) {
        return res.status(400).json({ success: false, message: 'Invalid pool_type. Allowed: coffee, other' });
      }
      const pool = await createPool({
        pool_name,
        description,
        price: Number(normalizedNetPrice.toFixed(2)),
        subscription_coffee_id,
        pool_type,
        is_active,
        created_by: actorUserId
      });
      return res.status(201).json({ success: true, data: pool });
    } catch (e) {
      if (e && (e.code === 'ER_DUP_ENTRY' || e.errno === 1062)) {
        return res.status(409).json({ success: false, message: 'Pool name already exists' });
      }
      if (e && e.status === 400) {
        return res.status(400).json({ success: false, message: e.message });
      }
      console.error('[PoolController.create]', e);
      return res.status(500).json({ success: false, message: 'Internal server error' });
    }
  },

  async list(req, res) {
    try {
      console.debug('[PoolController.list] GET /api/admin/pools');
      const pools = await listPools();
      return res.status(200).json({ success: true, data: pools });
    } catch (e) {
      console.error('[PoolController.list] error', e);
      return res.status(500).json({ success: false, message: 'Internal server error' });
    }
  },

  // Update pool active status
  async updateActive(req, res) {
    try {
      const { id } = req.params || {};
      const { is_active } = req.body || {};
      const actorUserId = req.user && req.user.userId;
      if (!id) return res.status(400).json({ success: false, message: 'id is required' });
      if (typeof is_active !== 'boolean') {
        return res.status(400).json({ success: false, message: 'is_active must be a boolean' });
      }
      const updated = await updatePoolState(id, is_active, actorUserId);
      return res.status(200).json({ success: true, data: updated });
    } catch (e) {
      if (e && e.status === 400) {
        return res.status(400).json({ success: false, message: e.message });
      }
      console.error('[PoolController.updateActive]', e);
      return res.status(500).json({ success: false, message: 'Internal server error' });
    }
  },

  async updateSubscription(req, res) {
    try {
      const { id } = req.params || {};
      const { subscription_coffee_id } = req.body || {};
      const actorUserId = req.user && req.user.userId;
      if (!id) return res.status(400).json({ success: false, message: 'id is required' });

      const updated = await updatePoolSubscription({
        id,
        subscription_coffee_id,
        actorUserId,
      });
      return res.status(200).json({ success: true, data: updated });
    } catch (e) {
      if (e && e.status === 400) {
        return res.status(400).json({ success: false, message: e.message });
      }
      console.error('[PoolController.updateSubscription]', e);
      return res.status(500).json({ success: false, message: 'Internal server error' });
    }
  },

  async listMembers(req, res) {
    try {
      const { id } = req.params || {};
      if (!id) return res.status(400).json({ success: false, message: 'id is required' });
      const members = await PoolMemberService.listMembers(id);
      return res.status(200).json({ success: true, members });
    } catch (e) {
      console.error('[PoolController.listMembers]', e);
      return res.status(500).json({ success: false, message: 'Internal server error' });
    }
  },

  async addMembers(req, res) {
    try {
      const { id } = req.params || {};
      const { userIds } = req.body || {};
      const actorUserId = req.user && req.user.userId;
      if (!id) return res.status(400).json({ success: false, message: 'id is required' });
      if (!Array.isArray(userIds) || userIds.length === 0) {
        return res.status(400).json({ success: false, message: 'userIds must be a non-empty array' });
      }
      await PoolMemberService.addMembers(id, userIds, actorUserId);
      return res.status(200).json({ success: true });
    } catch (e) {
      console.error('[PoolController.addMembers]', e);
      return res.status(500).json({ success: false, message: 'Internal server error' });
    }
  },

  async removeMembers(req, res) {
    try {
      const { id } = req.params || {};
      const { userIds } = req.body || {};
      const actorUserId = req.user && req.user.userId;
      if (!id) return res.status(400).json({ success: false, message: 'id is required' });
      if (!Array.isArray(userIds) || userIds.length === 0) {
        return res.status(400).json({ success: false, message: 'userIds must be a non-empty array' });
      }
      const removed = await PoolMemberService.removeMembers(id, userIds, actorUserId);
      return res.status(200).json({ success: true, removed });
    } catch (e) {
      console.error('[PoolController.removeMembers]', e);
      return res.status(500).json({ success: false, message: 'Internal server error' });
    }
  },

  async inflowDiagnostics(req, res) {
    try {
      const invoiceId = Number(req.query?.invoiceId);
      if (!Number.isFinite(invoiceId) || invoiceId <= 0) {
        return res.status(400).json({ success: false, message: 'invoiceId is required and must be a positive number' });
      }

      const data = await PoolInflowService.getInvoiceInflowDiagnostics({
        invoiceId,
        paidAt: req.query?.paidAt,
      });

      return res.status(200).json({ success: true, data });
    } catch (e) {
      console.error('[PoolController.inflowDiagnostics]', e);
      return res.status(500).json({ success: false, message: 'Internal server error' });
    }
  },

  async poolStats(req, res) {
    try {
      const poolId = Number(req.params?.id);
      if (!Number.isFinite(poolId) || poolId <= 0) {
        return res.status(400).json({ success: false, message: 'Invalid pool ID' });
      }

      const db = require('../../database/database');
      const now = new Date();
      const yearStart = new Date(now.getFullYear(), 0, 1).toISOString().slice(0, 10);
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().slice(0, 10);

      const [[totals]] = await db.query(
        `SELECT
           COALESCE(SUM(amount_net), 0) AS total_amount,
           COALESCE(SUM(CASE WHEN created_at >= ? THEN amount_net ELSE 0 END), 0) AS amount_this_year,
           COALESCE(SUM(CASE WHEN created_at >= ? THEN amount_net ELSE 0 END), 0) AS amount_this_month,
           COUNT(*) AS total_inflows
         FROM pool_inflows
         WHERE pool_id = ?`,
        [yearStart, monthStart, poolId]
      );

      return res.status(200).json({
        success: true,
        data: {
          total_amount: Number(totals?.total_amount ?? 0),
          amount_this_year: Number(totals?.amount_this_year ?? 0),
          amount_this_month: Number(totals?.amount_this_month ?? 0),
          total_inflows: Number(totals?.total_inflows ?? 0),
        },
      });
    } catch (e) {
      console.error('[PoolController.poolStats]', e);
      return res.status(500).json({ success: false, message: 'Internal server error' });
    }
  }
};