using Asp.Versioning;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using AdsAnalyticsService.API.Application.Commands;
using AdsAnalyticsService.API.Application.DTOs;
using AdsAnalyticsService.API.Application.Queries;
using AdsAnalyticsService.Domain.AggregatesModel.ReportAggregate;

namespace AdsAnalyticsService.API.Controllers;

/// <summary>
/// EN: API Controller for reports management.
/// VI: API Controller quản lý báo cáo.
/// </summary>
[ApiController]
[Authorize]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/ads-analytics/reports")]
[Produces("application/json")]
public class ReportsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<ReportsController> _logger;

    public ReportsController(IMediator mediator, ILogger<ReportsController> logger)
    {
        _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <summary>
    /// EN: Get list of reports for an advertiser.
    /// VI: Lấy danh sách báo cáo cho advertiser.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(List<ReportListDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<List<ReportListDto>>> GetReports(
        [FromQuery] Guid advertiserId,
        [FromQuery] int skip = 0,
        [FromQuery] int take = 20)
    {
        var query = new GetReportsQuery
        {
            AdvertiserId = advertiserId,
            Skip = skip,
            Take = take
        };

        var reports = await _mediator.Send(query);
        return Ok(new { success = true, data = reports });
    }

    /// <summary>
    /// EN: Create a new custom report.
    /// VI: Tạo báo cáo tùy chỉnh mới.
    /// </summary>
    [HttpPost]
    [ProducesResponseType(typeof(Guid), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<ActionResult<Guid>> CreateReport(
        [FromBody] CreateReportRequest request,
        [FromQuery] Guid advertiserId)
    {
        if (string.IsNullOrWhiteSpace(request.Name))
            return BadRequest(new { success = false, error = new { code = "BAD_REQUEST", message = "Report name is required" } });

        if (!Enum.TryParse<ReportType>(request.ReportType, out var reportType))
            return BadRequest(new { success = false, error = new { code = "BAD_REQUEST", message = "Invalid report type" } });

        var command = new CreateReportCommand
        {
            AdvertiserId = advertiserId,
            Name = request.Name,
            ReportType = reportType,
            StartDate = request.StartDate,
            EndDate = request.EndDate
        };

        var reportId = await _mediator.Send(command);

        return CreatedAtAction(nameof(GetReportById), new { id = reportId }, new { success = true, data = reportId });
    }

    /// <summary>
    /// EN: Get report by ID (placeholder).
    /// VI: Lấy báo cáo theo ID (placeholder).
    /// </summary>
    [HttpGet("{id}")]
    [ProducesResponseType(StatusCodes.Status501NotImplemented)]
    public IActionResult GetReportById(Guid id)
    {
        _logger.LogWarning("GetReportById not yet fully implemented");
        return StatusCode(StatusCodes.Status501NotImplemented,
            new { success = false, error = new { code = "NOT_IMPLEMENTED", message = "Get report by ID endpoint not yet implemented" } });
    }

    /// <summary>
    /// EN: Schedule recurring report (placeholder).
    /// VI: Lên lịch báo cáo định kỳ (placeholder).
    /// </summary>
    [HttpPost("schedule")]
    [ProducesResponseType(StatusCodes.Status501NotImplemented)]
    public IActionResult ScheduleReport([FromBody] ScheduleReportRequest request)
    {
        _logger.LogWarning("ScheduleReport not yet implemented");
        return StatusCode(StatusCodes.Status501NotImplemented,
            new { success = false, error = new { code = "NOT_IMPLEMENTED", message = "Schedule report endpoint will be implemented in future version" } });
    }

    /// <summary>
    /// EN: Export report (placeholder).
    /// VI: Export báo cáo (placeholder).
    /// </summary>
    [HttpGet("{id}/export")]
    [ProducesResponseType(StatusCodes.Status501NotImplemented)]
    public IActionResult ExportReport(Guid id, [FromQuery] string format = "csv")
    {
        _logger.LogWarning("ExportReport not yet implemented");
        return StatusCode(StatusCodes.Status501NotImplemented,
            new { success = false, error = new { code = "NOT_IMPLEMENTED", message = "Export report endpoint will be implemented in future version" } });
    }
}
