import * as timesheetService from '../services/timesheet.service.js';
import { ForbiddenError } from '../utils/errors.js';

/**
 * Upload timesheet
 * POST /api/timesheets/upload
 */
export const uploadTimesheet = async (req, res, next) => {
  try {
    const { year, month, userId: requestUserId } = req.body;

    // Determine target userId:
    // - If requestUserId is provided and user is admin/team_leader, use requestUserId
    // - Otherwise, use req.userId (upload for themselves)
    let targetUserId = req.userId;
    const hasFullAccess = req.user.role === 'admin' || req.user.role === 'team_leader';
    if (requestUserId) {
      if (!hasFullAccess) {
        throw new ForbiddenError('Iba admin alebo team leader môže nahrávať timesheets za iných používateľov');
      }
      targetUserId = requestUserId;
    }

    const timesheet = await timesheetService.uploadTimesheet({
      userId: targetUserId,
      year,
      month,
      file: req.file,
      auditContext: { userId: req.userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] },
    });

    res.status(201).json({
      success: true,
      data: { timesheet },
      message: 'Timesheet bol úspešne nahraný',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get user's timesheets (with optional filters)
 * GET /api/timesheets/my
 */
export const getMyTimesheets = async (req, res, next) => {
  try {
    const { year, month } = req.query;

    const userTimesheets = await timesheetService.getTimesheetsForUser(req.userId, { year, month });

    res.status(200).json({
      success: true,
      data: {
        timesheets: userTimesheets,
        count: userTimesheets.length,
      },
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get all users' timesheets (admin only) - grouped by user
 * GET /api/timesheets/all
 */
export const getAllTimesheets = async (req, res, next) => {
  try {
    const { userId, year, month } = req.query;

    const allTimesheets = await timesheetService.getAllTimesheets({ userId, year, month });

    res.status(200).json({
      success: true,
      data: {
        timesheets: allTimesheets,
        count: allTimesheets.length,
      },
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Download timesheet file
 * GET /api/timesheets/:timesheetId/download
 */
export const downloadTimesheet = async (req, res, next) => {
  try {
    const { timesheetId } = req.params;
    const { filePath, fileName } = await timesheetService.getDownloadInfo(timesheetId, {
      userId: req.userId,
      role: req.user.role,
    });

    res.download(filePath, fileName);
  } catch (error) {
    next(error);
  }
};

/**
 * Delete timesheet
 * DELETE /api/timesheets/:timesheetId
 */
export const deleteTimesheet = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { timesheetId } = req.params;

    await timesheetService.deleteTimesheet(timesheetId, {
      userId,
      role: req.user.role,
    }, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(200).json({
      success: true,
      message: 'Timesheet bol zmazaný',
    });
  } catch (error) {
    next(error);
  }
};
