using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AdsAnalyticsService.API.Application.DTOs;
using AdsAnalyticsService.Infrastructure;

namespace AdsAnalyticsService.API.Controllers.Admin;

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

    public AdminReportsController(
        AdsAnalyticsServiceContext context,
        ILogger<AdminReportsController> logger)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <summary>
    /// EN: Get all reports across all advertisers.
    /// VI: Lấy tất cả báo cáo từ tất cả advertisers.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(List<ReportListDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<List<ReportListDto>>> GetAllReports(
        [FromQuery] int skip = 0,
        [FromQuery] int take = 50)
    {
        var reports = await _context.Reports
            .OrderByDescending(r => r.CreatedAt)
            .Skip(skip)
            .Take(take)
            .Select(r => new ReportListDto(
                r.Id,
                r.Name,
                r.ReportType.ToString(),
                r.StartDate,
                r.EndDate,
                r.Status.ToString(),
                r.CreatedAt))
            .ToListAsync();

        _logger.LogInformation("Admin retrieved {Count} reports", reports.Count);

        return Ok(new { success = true, data = reports });
    }

    /// <summary>
    /// EN: Delete a report (admin only).
    /// VI: Xóa báo cáo (chỉ admin).
    /// </summary>
    [HttpDelete("{id}")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> DeleteReport(Guid id)
    {
        var report = await _context.Reports.FindAsync(id);
        
        if (report == null)
            return NotFound(new { success = false, error = new { code = "NOT_FOUND", message = $"Report {id} not found" } });

        _context.Reports.Remove(report);
        await _context.SaveChangesAsync();

        _logger.LogInformation("Admin deleted report {ReportId}", id);

        return NoContent();
    }
}
