using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SIGCM.Domain.Entities;
using SIGCM.Domain.Interfaces;
using SIGCM.Infrastructure.Repositories;
using SIGCM.Domain.Models;

namespace SIGCM.API.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class ClaimsController : ControllerBase
{
  private readonly IClaimRepository _repository;
  private readonly AuditRepository _auditRepo;

  public ClaimsController(IClaimRepository repository, AuditRepository auditRepo)
  {
    _repository = repository;
    _auditRepo = auditRepo;
  }

  [HttpPost]
  public async Task<IActionResult> Create(Claim claim)
  {
    System.Security.Claims.Claim? userIdClaim = User.FindFirst("Id");
    var userId = int.Parse(userIdClaim?.Value!);
    claim.CreatedByUserId = userId;
    claim.CreatedAt = DateTime.UtcNow;
    claim.Status = "Open";

    var id = await _repository.CreateAsync(claim);

    await _auditRepo.AddLogAsync(new AuditLog
    {
      UserId = userId,
      Action = "CLAIM_CREATED",
      EntityId = id,
      EntityType = "Claim",
      Details = $"Reclamo creado para aviso {claim.ListingId}: {claim.ClaimType}"
    });

    return Ok(new { id });
  }

  [HttpGet("listing/{listingId}")]
  public async Task<IActionResult> GetByListing(int listingId)
  {
    var claims = await _repository.GetByListingIdAsync(listingId);
    return Ok(claims);
  }

  [HttpPut("{id}/resolve")]
  public async Task<IActionResult> Resolve(int id, [FromBody] ResolveRequest request)
  {
    var userIdClaim = User.FindFirst("Id")?.Value;
    if (!int.TryParse(userIdClaim, out int userId)) return Unauthorized();

    // Llamamos al repositorio pasando el objeto completo de solicitud
    await _repository.UpdateStatusAsync(id, "Resolved", request, userId);

    await _auditRepo.AddLogAsync(new AuditLog
    {
      UserId = userId,
      Action = "CLAIM_RESOLVED_TECHNICAL",
      EntityId = id,
      EntityType = "Claim",
      Details = $"Reclamo {id} resuelto con ajustes técnicos aplicados."
    });

    return Ok(new { message = "Reclamo resuelto y aviso actualizado." });
  }
}