/**
 * Finance Controller
 * Handles payroll runs and payslips
 */

const express = require('express');
const router = express.Router();
const path = require('path');
const Database = require('better-sqlite3');
const { v4: uuidv4 } = require('uuid');

const dbPath = process.env.DB_PATH || path.join(__dirname, '../../data/school.db');
const db = new Database(dbPath);
db.pragma('foreign_keys = ON');

// Auth middleware
const auth = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'No token provided' });
  try {
    const jwt = require('jsonwebtoken');
    const JWT_SECRET = process.env.JWT_SECRET || 'africa-alert-secret-key-2024';
    req.user = jwt.verify(token, JWT_SECRET);
    next();
  } catch (err) {
    res.status(401).json({ error: 'Invalid token' });
  }
};

const financeAccess = (req, res, next) => {
  const allowedRoles = ['admin', 'principal', 'bursar', 'accountant'];
  if (!allowedRoles.includes(req.user.role)) {
    return res.status(403).json({ error: 'Finance, Bursar, Accountant, Principal or Admin access required' });
  }
  next();
};

const adminOnly = (req, res, next) => {
  if (req.user.role !== 'admin' && req.user.role !== 'principal') {
    return res.status(403).json({ error: 'Admin or Principal access required' });
  }
  next();
};

// ============ PAYROLL RUNS ============

router.get('/payroll/runs', auth, financeAccess, (req, res) => {
  const runs = db.prepare('SELECT * FROM payroll_runs WHERE is_deleted = 0 ORDER BY period_year DESC, period_month DESC').all();
  res.json(runs);
});

router.post('/payroll/runs', auth, financeAccess, (req, res) => {
  const { period_month, period_year, description } = req.body;
  const uid = uuidv4();
  const result = db.prepare(`
    INSERT INTO payroll_runs (uid, period_month, period_year, description, status, created_by, sync_status)
    VALUES (?, ?, ?, ?, 'draft', ?, 'pending')
  `).run(uid, period_month, period_year, description, req.user.id);
  res.json({ id: result.lastInsertRowid, uid });
});

// ============ PAYSLIPS ============

router.get('/payroll/payslips', auth, (req, res) => {
  const isPrivileged = ['admin', 'principal', 'bursar', 'accountant'].includes(req.user.role);
  
  const query = isPrivileged
    ? 'SELECT p.*, u.first_name, u.last_name, r.period_month, r.period_year FROM payslips p JOIN users u ON p.staff_id = u.id JOIN payroll_runs r ON p.payroll_run_id = r.id WHERE p.is_deleted = 0'
    : 'SELECT p.*, r.period_month, r.period_year FROM payslips p JOIN payroll_runs r ON p.payroll_run_id = r.id WHERE p.staff_id = ? AND p.is_deleted = 0';
  
  const params = isPrivileged ? [] : [req.user.id];
  const payslips = db.prepare(query).all(...params);
  res.json(payslips);
});

router.post('/payroll/payslips/generate', auth, financeAccess, (req, res) => {
  const { payroll_run_id } = req.body;
  
  // Get all active staff records with their salary grades
  const staff = db.prepare(`
    SELECT sr.*, sg.basic_salary, sg.housing_allowance, sg.transport_allowance, sg.medical_allowance, sg.other_allowances
    FROM staff_records sr
    JOIN salary_grades sg ON sr.salary_grade_id = sg.id
    WHERE sr.is_active = 1 AND sr.is_deleted = 0
  `).all();

  const insert = db.prepare(`
    INSERT INTO payslips (uid, staff_id, payroll_run_id, basic_salary, housing_allowance, transport_allowance, medical_allowance, other_allowances, gross_salary, net_salary, status, sync_status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'pending')
  `);

  const transaction = db.transaction((staffMembers) => {
    for (const member of staffMembers) {
      const gross = member.basic_salary + member.housing_allowance + member.transport_allowance + member.medical_allowance + member.other_allowances;
      const net = gross; // Simplified for now
      insert.run(uuidv4(), member.user_id, payroll_run_id, member.basic_salary, member.housing_allowance, member.transport_allowance, member.medical_allowance, member.other_allowances, gross, net);
    }
  });

  transaction(staff);
  res.json({ success: true, count: staff.length });
});

module.exports = router;
