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

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

    // Determine target userId:
    // - If requestUserId is provided and user is admin, use requestUserId
    // - Otherwise, use req.userId (upload for themselves)
    let targetUserId = req.userId;
    if (requestUserId) {
      if (req.user.role !== 'admin') {
        const errorResponse = formatErrorResponse(
          new Error('Iba admin môže nahrávať timesheets za iných používateľov'),
          process.env.NODE_ENV === 'development'
        );
        return res.status(403).json(errorResponse);
      }
      targetUserId = requestUserId;
    }

    const timesheet = await timesheetService.uploadTimesheet({
      userId: targetUserId,
      year,
      month,
      file: req.file,
    });

    res.status(201).json({
      success: true,
      data: { timesheet },
      message: 'Timesheet bol úspešne nahraný',
    });
  } catch (error) {
    const errorResponse = formatErrorResponse(error, process.env.NODE_ENV === 'development');
    res.status(error.statusCode || 500).json(errorResponse);
  }
};

/**
 * Get user's timesheets (with optional filters)
 * GET /api/timesheets/my
 */
export const getMyTimesheets = async (req, res) => {
  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) {
    const errorResponse = formatErrorResponse(error, process.env.NODE_ENV === 'development');
    res.status(error.statusCode || 500).json(errorResponse);
  }
};

/**
 * Get all users' timesheets (admin only) - grouped by user
 * GET /api/timesheets/all
 */
export const getAllTimesheets = async (req, res) => {
  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) {
    const errorResponse = formatErrorResponse(error, process.env.NODE_ENV === 'development');
    res.status(error.statusCode || 500).json(errorResponse);
  }
};

/**
 * Download timesheet file
 * GET /api/timesheets/:timesheetId/download
 */
export const downloadTimesheet = async (req, res) => {
  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) {
    const errorResponse = formatErrorResponse(error, process.env.NODE_ENV === 'development');
    res.status(error.statusCode || 500).json(errorResponse);
  }
};

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

    await timesheetService.deleteTimesheet(timesheetId, {
      userId: req.userId,
      role: req.user.role,
    });

    res.status(200).json({
      success: true,
      message: 'Timesheet bol zmazaný',
    });
  } catch (error) {
    const errorResponse = formatErrorResponse(error, process.env.NODE_ENV === 'development');
    res.status(error.statusCode || 500).json(errorResponse);
  }
};
