using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SIGCM.Application.DTOs;
using SIGCM.Domain.Interfaces;

namespace SIGCM.API.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class ProfileController : ControllerBase
{
    private readonly IUserRepository _userRepo;

    public ProfileController(IUserRepository userRepo)
    {
        _userRepo = userRepo;
    }

    [HttpGet]
    public async Task<IActionResult> GetProfile()
    {
        var userIdStr = User.FindFirst("Id")?.Value;
        if (!int.TryParse(userIdStr, out int userId)) return Unauthorized();

        var user = await _userRepo.GetByIdAsync(userId);
        if (user == null) return NotFound();

        return Ok(new
        {
            user.Username,
            user.Email,
            user.BillingName,
            user.BillingAddress,
            user.BillingTaxId,
            user.BillingTaxType
        });
    }

    [HttpPut]
    public async Task<IActionResult> UpdateProfile(UpdateProfileDto dto)
    {
        var userIdStr = User.FindFirst("Id")?.Value;
        if (!int.TryParse(userIdStr, out int userId)) return Unauthorized();

        var user = await _userRepo.GetByIdAsync(userId);
        if (user == null) return NotFound();

        user.Email = dto.Email;
        user.BillingName = dto.BillingName;
        user.BillingAddress = dto.BillingAddress;
        user.BillingTaxId = dto.BillingTaxId;
        user.BillingTaxType = dto.BillingTaxType;

        await _userRepo.UpdateAsync(user);
        return Ok(new
        {
            user.Username,
            user.Email,
            user.BillingName,
            user.BillingAddress,
            user.BillingTaxId,
            user.BillingTaxType
        });
    }
}
