using MediatR;
using Microsoft.AspNetCore.Mvc;
using ColaFlow.Modules.ProjectManagement.Application.DTOs;
using ColaFlow.Modules.ProjectManagement.Application.Commands.CreateTask;
using ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTask;
using ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteTask;
using ColaFlow.Modules.ProjectManagement.Application.Commands.AssignTask;
using ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTaskStatus;
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetTaskById;
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByStoryId;
using ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByProjectId;

namespace ColaFlow.API.Controllers;

/// <summary>
/// Tasks API Controller
/// </summary>
[ApiController]
[Route("api/v1")]
public class TasksController(IMediator mediator) : ControllerBase
{
    private readonly IMediator _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));

    /// <summary>
    /// Get task by ID
    /// </summary>
    [HttpGet("tasks/{id:guid}")]
    [ProducesResponseType(typeof(TaskDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetTask(Guid id, CancellationToken cancellationToken = default)
    {
        var query = new GetTaskByIdQuery(id);
        var result = await _mediator.Send(query, cancellationToken);

        if (result == null)
        {
            return NotFound();
        }

        return Ok(result);
    }

    /// <summary>
    /// Get all tasks for a story
    /// </summary>
    [HttpGet("stories/{storyId:guid}/tasks")]
    [ProducesResponseType(typeof(List<TaskDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetStoryTasks(Guid storyId, CancellationToken cancellationToken = default)
    {
        var query = new GetTasksByStoryIdQuery(storyId);
        var result = await _mediator.Send(query, cancellationToken);
        return Ok(result);
    }

    /// <summary>
    /// Get all tasks for a project (for Kanban board)
    /// </summary>
    [HttpGet("projects/{projectId:guid}/tasks")]
    [ProducesResponseType(typeof(List<TaskDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetProjectTasks(
        Guid projectId,
        [FromQuery] string? status = null,
        [FromQuery] Guid? assigneeId = null,
        CancellationToken cancellationToken = default)
    {
        var query = new GetTasksByProjectIdQuery
        {
            ProjectId = projectId,
            Status = status,
            AssigneeId = assigneeId
        };
        var result = await _mediator.Send(query, cancellationToken);
        return Ok(result);
    }

    /// <summary>
    /// Create a new task (independent endpoint)
    /// </summary>
    [HttpPost("tasks")]
    [ProducesResponseType(typeof(TaskDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> CreateTaskIndependent(
        [FromBody] CreateTaskCommand command,
        CancellationToken cancellationToken = default)
    {
        var result = await _mediator.Send(command, cancellationToken);
        return CreatedAtAction(nameof(GetTask), new { id = result.Id }, result);
    }

    /// <summary>
    /// Create a new task (nested endpoint)
    /// </summary>
    [HttpPost("stories/{storyId:guid}/tasks")]
    [ProducesResponseType(typeof(TaskDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> CreateTask(
        Guid storyId,
        [FromBody] CreateTaskRequest request,
        CancellationToken cancellationToken = default)
    {
        var command = new CreateTaskCommand
        {
            StoryId = storyId,
            Title = request.Title,
            Description = request.Description,
            Priority = request.Priority,
            EstimatedHours = request.EstimatedHours,
            AssigneeId = request.AssigneeId,
            CreatedBy = request.CreatedBy
        };

        var result = await _mediator.Send(command, cancellationToken);
        return CreatedAtAction(nameof(GetTask), new { id = result.Id }, result);
    }

    /// <summary>
    /// Update an existing task
    /// </summary>
    [HttpPut("tasks/{id:guid}")]
    [ProducesResponseType(typeof(TaskDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> UpdateTask(
        Guid id,
        [FromBody] UpdateTaskRequest request,
        CancellationToken cancellationToken = default)
    {
        var command = new UpdateTaskCommand
        {
            TaskId = id,
            Title = request.Title,
            Description = request.Description,
            Status = request.Status,
            Priority = request.Priority,
            EstimatedHours = request.EstimatedHours,
            AssigneeId = request.AssigneeId
        };

        var result = await _mediator.Send(command, cancellationToken);

        if (result == null)
        {
            return NotFound();
        }

        return Ok(result);
    }

    /// <summary>
    /// Delete a task
    /// </summary>
    [HttpDelete("tasks/{id:guid}")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> DeleteTask(Guid id, CancellationToken cancellationToken = default)
    {
        var command = new DeleteTaskCommand { TaskId = id };
        await _mediator.Send(command, cancellationToken);
        return NoContent();
    }

    /// <summary>
    /// Assign a task to a user
    /// </summary>
    [HttpPut("tasks/{id:guid}/assign")]
    [ProducesResponseType(typeof(TaskDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> AssignTask(
        Guid id,
        [FromBody] AssignTaskRequest request,
        CancellationToken cancellationToken = default)
    {
        var command = new AssignTaskCommand
        {
            TaskId = id,
            AssigneeId = request.AssigneeId
        };

        var result = await _mediator.Send(command, cancellationToken);

        if (result == null)
        {
            return NotFound();
        }

        return Ok(result);
    }

    /// <summary>
    /// Update task status (for Kanban board drag & drop)
    /// </summary>
    [HttpPut("tasks/{id:guid}/status")]
    [ProducesResponseType(typeof(TaskDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> UpdateTaskStatus(
        Guid id,
        [FromBody] UpdateTaskStatusRequest request,
        CancellationToken cancellationToken = default)
    {
        var command = new UpdateTaskStatusCommand
        {
            TaskId = id,
            NewStatus = request.NewStatus
        };

        var result = await _mediator.Send(command, cancellationToken);

        if (result == null)
        {
            return NotFound();
        }

        return Ok(result);
    }
}

/// <summary>
/// Request model for creating a task
/// </summary>
public record CreateTaskRequest
{
    public string Title { get; init; } = string.Empty;
    public string Description { get; init; } = string.Empty;
    public string Priority { get; init; } = "Medium";
    public decimal? EstimatedHours { get; init; }
    public Guid? AssigneeId { get; init; }
    public Guid CreatedBy { get; init; }
}

/// <summary>
/// Request model for updating a task
/// </summary>
public record UpdateTaskRequest
{
    public string Title { get; init; } = string.Empty;
    public string Description { get; init; } = string.Empty;
    public string? Status { get; init; }
    public string? Priority { get; init; }
    public decimal? EstimatedHours { get; init; }
    public Guid? AssigneeId { get; init; }
}

/// <summary>
/// Request model for assigning a task
/// </summary>
public record AssignTaskRequest
{
    public Guid? AssigneeId { get; init; }
}

/// <summary>
/// Request model for updating task status
/// </summary>
public record UpdateTaskStatusRequest
{
    public string NewStatus { get; init; } = string.Empty;
}
