import * as timeTrackingService from '../services/time-tracking.service.js';

/**
 * Start a new time entry
 * POST /api/time-tracking/start
 */
export const startTimeEntry = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { projectId, todoId, companyId, description } = req.body;

    const entry = await timeTrackingService.startTimeEntry(userId, {
      projectId,
      todoId,
      companyId,
      description,
    }, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(201).json({
      success: true,
      data: entry,
      message: 'Časovač bol spustený',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Stop a running time entry
 * POST /api/time-tracking/:entryId/stop
 */
export const stopTimeEntry = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { entryId } = req.params;
    const { projectId, todoId, companyId, description } = req.body;

    const entry = await timeTrackingService.stopTimeEntry(entryId, userId, {
      projectId,
      todoId,
      companyId,
      description,
    }, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(200).json({
      success: true,
      data: entry,
      message: 'Časovač bol zastavený',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Pause a running time entry
 * POST /api/time-tracking/:entryId/pause
 */
export const pauseTimeEntry = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { entryId } = req.params;

    const entry = await timeTrackingService.pauseTimeEntry(entryId, userId, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(200).json({
      success: true,
      data: entry,
      message: 'Časovač bol pozastavený',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Resume a paused time entry
 * POST /api/time-tracking/:entryId/resume
 */
export const resumeTimeEntry = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { entryId } = req.params;

    const entry = await timeTrackingService.resumeTimeEntry(entryId, userId, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(200).json({
      success: true,
      data: entry,
      message: 'Časovač bol obnovený',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get running time entry for current user
 * GET /api/time-tracking/running
 */
export const getRunningTimeEntry = async (req, res, next) => {
  try {
    const userId = req.userId;

    const entry = await timeTrackingService.getRunningTimeEntry(userId);

    res.status(200).json({
      success: true,
      data: entry,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get all running time entries (for dashboard)
 * GET /api/time-tracking/running-all
 */
export const getAllRunningTimeEntries = async (req, res, next) => {
  try {
    const entries = await timeTrackingService.getAllRunningTimeEntries();

    res.status(200).json({
      success: true,
      data: entries,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get all time entries for current user with filters
 * GET /api/time-tracking?projectId=xxx&todoId=xxx&companyId=xxx&startDate=xxx&endDate=xxx
 */
export const getAllTimeEntries = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { projectId, todoId, companyId, startDate, endDate } = req.query;

    const filters = {
      projectId,
      todoId,
      companyId,
      startDate,
      endDate,
    };

    const entries = await timeTrackingService.getAllTimeEntries(userId, filters);

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

/**
 * Get time entries for a specific month
 * GET /api/time-tracking/month/:year/:month
 */
export const getMonthlyTimeEntries = async (req, res, next) => {
  try {
    const userId = req.userId;
    const userRole = req.user.role;
    const hasFullAccess = userRole === 'admin' || userRole === 'team_leader';
    const targetUserId = hasFullAccess && req.query.userId ? req.query.userId : userId;
    const { year, month } = req.params;

    const entries = await timeTrackingService.getMonthlyTimeEntries(
      targetUserId,
      parseInt(year),
      parseInt(month)
    );

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

/**
 * Generate timesheet file for a month
 * POST /api/time-tracking/month/:year/:month/generate
 */
export const generateMonthlyTimesheet = async (req, res, next) => {
  try {
    const userId = req.userId;
    const userRole = req.user.role;
    const hasFullAccess = userRole === 'admin' || userRole === 'team_leader';
    const targetUserId = hasFullAccess && req.query.userId ? req.query.userId : userId;
    const { year, month } = req.params;

    const result = await timeTrackingService.generateMonthlyTimesheet(
      targetUserId,
      parseInt(year),
      parseInt(month)
    );

    res.status(201).json({
      success: true,
      data: result,
      message: 'Timesheet bol vygenerovaný',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get time entry by ID
 * GET /api/time-tracking/:entryId
 */
export const getTimeEntryById = async (req, res, next) => {
  try {
    const { entryId } = req.params;

    const entry = await timeTrackingService.getTimeEntryById(entryId);

    res.status(200).json({
      success: true,
      data: entry,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get time entry with related data
 * GET /api/time-tracking/:entryId/details
 */
export const getTimeEntryWithRelations = async (req, res, next) => {
  try {
    const { entryId } = req.params;

    const entry = await timeTrackingService.getTimeEntryWithRelations(entryId);

    res.status(200).json({
      success: true,
      data: entry,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Update time entry
 * PATCH /api/time-tracking/:entryId
 */
export const updateTimeEntry = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { entryId } = req.params;
    const { startTime, endTime, projectId, todoId, companyId, description } = req.body;

    const entry = await timeTrackingService.updateTimeEntry(entryId, {
      userId,
      role: req.user.role,
    }, {
      startTime,
      endTime,
      projectId,
      todoId,
      companyId,
      description,
    }, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(200).json({
      success: true,
      data: entry,
      message: 'Záznam bol aktualizovaný',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Delete time entry
 * DELETE /api/time-tracking/:entryId
 */
export const deleteTimeEntry = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { entryId } = req.params;

    const result = await timeTrackingService.deleteTimeEntry(entryId, {
      userId,
      role: req.user.role,
    }, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(200).json(result);
  } catch (error) {
    next(error);
  }
};

/**
 * Get monthly statistics
 * GET /api/time-tracking/stats/monthly/:year/:month
 */
export const getMonthlyStats = async (req, res, next) => {
  try {
    const userId = req.userId;
    const userRole = req.user.role;
    const hasFullAccess = userRole === 'admin' || userRole === 'team_leader';
    const targetUserId = hasFullAccess && req.query.userId ? req.query.userId : userId;
    const { year, month } = req.params;

    const stats = await timeTrackingService.getMonthlyStats(
      targetUserId,
      parseInt(year),
      parseInt(month)
    );

    res.status(200).json({
      success: true,
      data: stats,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Generate timesheet for a specific company
 * POST /api/time-tracking/generate-company-timesheet
 * Body: { year, month, companyId }
 */
export const generateCompanyTimesheet = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { year, month, companyId } = req.body;

    if (!year || !month || !companyId) {
      return res.status(400).json({
        success: false,
        message: 'Year, month and companyId are required',
      });
    }

    const result = await timeTrackingService.generateCompanyTimesheet(
      userId,
      parseInt(year),
      parseInt(month),
      companyId
    );

    res.status(201).json({
      success: true,
      data: result,
      message: `Timesheet pre firmu ${result.companyName} bol vygenerovaný`,
    });
  } catch (error) {
    next(error);
  }
};
