const { query } = require('../config/db');

// ─────────────────────────────────────────────────────────────────
// GET /api/leave/types
// Returns all active leave types for the org
// ─────────────────────────────────────────────────────────────────
async function getLeaveTypes(req, res) {
  try {
    const { org_id } = req.user;
    const { rows } = await query(
      `SELECT id, name, default_days_per_year, is_paid, color
       FROM leave_types
       WHERE org_id = $1 AND is_deleted = false
       ORDER BY name`,
      [org_id]
    );
    res.json({ success: true, data: rows });
  } catch (err) {
    console.error('getLeaveTypes:', err);
    res.status(500).json({ success: false, message: 'Internal server error' });
  }
}

// ─────────────────────────────────────────────────────────────────
// POST /api/leave/types
// Create a new leave type (admin/hr only)
// Body: { name, default_days_per_year, is_paid, color }
// ─────────────────────────────────────────────────────────────────
async function createLeaveType(req, res) {
  const { name, default_days_per_year = 12, is_paid = true, color = '#1D9E75' } = req.body;
  const { org_id, id: created_by } = req.user;

  if (!name) return res.status(422).json({ success: false, message: 'name is required' });

  try {
    const { rows } = await query(
      `INSERT INTO leave_types (name, default_days_per_year, is_paid, color, org_id, created_by)
       VALUES ($1, $2, $3, $4, $5, $6)
       RETURNING id, name, default_days_per_year, is_paid, color`,
      [name, default_days_per_year, is_paid, color, org_id, created_by]
    );
    res.status(201).json({ success: true, data: rows[0] });
  } catch (err) {
    if (err.code === '23505') {
      return res.status(409).json({ success: false, message: 'Leave type name already exists' });
    }
    console.error('createLeaveType:', err);
    res.status(500).json({ success: false, message: 'Internal server error' });
  }
}

// ─────────────────────────────────────────────────────────────────
// PATCH /api/leave/types/:id
// ─────────────────────────────────────────────────────────────────
async function updateLeaveType(req, res) {
  const { id } = req.params;
  const { name, default_days_per_year, is_paid, color } = req.body;
  const { org_id, id: updated_by } = req.user;

  try {
    const { rows } = await query(
      `UPDATE leave_types
       SET name = COALESCE($1, name),
           default_days_per_year = COALESCE($2, default_days_per_year),
           is_paid  = COALESCE($3, is_paid),
           color    = COALESCE($4, color),
           updated_by = $5,
           updated_at = NOW()
       WHERE id = $6 AND org_id = $7 AND is_deleted = false
       RETURNING id, name, default_days_per_year, is_paid, color`,
      [name, default_days_per_year, is_paid, color, updated_by, id, org_id]
    );
    if (!rows.length) return res.status(404).json({ success: false, message: 'Leave type not found' });
    res.json({ success: true, data: rows[0] });
  } catch (err) {
    console.error('updateLeaveType:', err);
    res.status(500).json({ success: false, message: 'Internal server error' });
  }
}

// ─────────────────────────────────────────────────────────────────
// DELETE /api/leave/types/:id  (soft delete)
// ─────────────────────────────────────────────────────────────────
async function deleteLeaveType(req, res) {
  const { id } = req.params;
  const { org_id, id: updated_by } = req.user;

  try {
    const { rowCount } = await query(
      `UPDATE leave_types
       SET is_deleted = true, updated_by = $1, updated_at = NOW()
       WHERE id = $2 AND org_id = $3 AND is_deleted = false`,
      [updated_by, id, org_id]
    );
    if (!rowCount) return res.status(404).json({ success: false, message: 'Leave type not found' });
    res.json({ success: true, message: 'Leave type deleted' });
  } catch (err) {
    console.error('deleteLeaveType:', err);
    res.status(500).json({ success: false, message: 'Internal server error' });
  }
}

module.exports = { getLeaveTypes, createLeaveType, updateLeaveType, deleteLeaveType };