import * as projectService from '../services/project.service.js';
import * as noteService from '../services/note.service.js';

/**
 * Get all projects
 * GET /api/projects?search=query&companyId=xxx
 * Members only see projects they are assigned to or projects of companies they are assigned to
 */
export const getAllProjects = async (req, res, next) => {
  try {
    const { search, companyId } = req.query;
    const userId = req.user?.id;
    const userRole = req.user?.role;

    const projects = await projectService.getAllProjects(search, companyId, userId, userRole);

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

/**
 * Get project by ID
 * GET /api/projects/:projectId
 */
export const getProjectById = async (req, res, next) => {
  try {
    const { projectId } = req.params;

    const project = await projectService.getProjectById(projectId);

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

/**
 * Get project with relations (company, todos, notes, timesheets)
 * GET /api/projects/:projectId/details
 */
export const getProjectWithRelations = async (req, res, next) => {
  try {
    const { projectId } = req.params;

    const project = await projectService.getProjectWithRelations(projectId);

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

/**
 * Create new project
 * POST /api/projects
 * Body: { name, description, companyId, status, startDate, endDate }
 */
export const createProject = async (req, res, next) => {
  try {
    const userId = req.userId;
    const data = req.body;

    const project = await projectService.createProject(userId, data, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(201).json({
      success: true,
      data: project,
      message: 'Projekt bol vytvorený',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Update project
 * PATCH /api/projects/:projectId
 * Body: { name, description, companyId, status, startDate, endDate }
 */
export const updateProject = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { projectId } = req.params;
    const data = req.body;

    const project = await projectService.updateProject(projectId, data, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(200).json({
      success: true,
      data: project,
      message: 'Projekt bol aktualizovaný',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Delete project
 * DELETE /api/projects/:projectId
 */
export const deleteProject = async (req, res, next) => {
  try {
    const { projectId } = req.params;
    const userId = req.userId;

    const result = await projectService.deleteProject(projectId, { userId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

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

/**
 * Get project notes
 * GET /api/projects/:projectId/notes
 */
export const getProjectNotes = async (req, res, next) => {
  try {
    const { projectId } = req.params;

    const notes = await noteService.getNotesByProjectId(projectId);

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

/**
 * Add project note
 * POST /api/projects/:projectId/notes
 */
export const addProjectNote = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { projectId } = req.params;
    const { content, dueDate } = req.body;

    const note = await noteService.createNote(userId, {
      content,
      projectId,
      dueDate,
    });

    res.status(201).json({
      success: true,
      data: note,
      message: 'Poznámka bola pridaná',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Update project note
 * PATCH /api/projects/:projectId/notes/:noteId
 */
export const updateProjectNote = async (req, res, next) => {
  try {
    const { noteId } = req.params;
    const { content, dueDate } = req.body;

    const note = await noteService.updateNote(noteId, {
      content,
      dueDate,
    });

    res.status(200).json({
      success: true,
      data: note,
      message: 'Poznámka bola aktualizovaná',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Delete project note
 * DELETE /api/projects/:projectId/notes/:noteId
 */
export const deleteProjectNote = async (req, res, next) => {
  try {
    const { noteId } = req.params;

    const result = await noteService.deleteNote(noteId);

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

/**
 * Get project users (team members)
 * GET /api/projects/:projectId/users
 */
export const getProjectUsers = async (req, res, next) => {
  try {
    const { projectId } = req.params;

    const users = await projectService.getProjectUsers(projectId);

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

/**
 * Assign user to project
 * POST /api/projects/:projectId/users
 * Body: { userId, role }
 */
export const assignUserToProject = async (req, res, next) => {
  try {
    const currentUserId = req.userId;
    const { projectId } = req.params;
    const { userId, role } = req.body;

    const assignment = await projectService.assignUserToProject(
      projectId,
      userId,
      currentUserId,
      role,
      { userId: currentUserId, ipAddress: req.ip, userAgent: req.headers['user-agent'] }
    );

    res.status(201).json({
      success: true,
      data: assignment,
      message: 'Používateľ bol priradený k projektu',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Remove user from project
 * DELETE /api/projects/:projectId/users/:userId
 */
export const removeUserFromProject = async (req, res, next) => {
  try {
    const currentUserId = req.userId;
    const { projectId, userId } = req.params;

    const result = await projectService.removeUserFromProject(projectId, userId, { userId: currentUserId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

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

/**
 * Update user role on project
 * PATCH /api/projects/:projectId/users/:userId
 * Body: { role }
 */
export const updateUserRoleOnProject = async (req, res, next) => {
  try {
    const { projectId, userId } = req.params;
    const { role } = req.body;

    const updated = await projectService.updateUserRoleOnProject(projectId, userId, role);

    res.status(200).json({
      success: true,
      data: updated,
      message: 'Rola používateľa bola aktualizovaná',
    });
  } catch (error) {
    next(error);
  }
};
