using CharacterApi.Models;
using CharacterApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace CharacterApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class CharactersController : ControllerBase
{
    private readonly CharacterStore _characters;

    public CharactersController(CharacterStore characters)
    {
        _characters = characters;
    }

    [HttpPost]
    [Authorize(Roles = "USER,SUPER")]
    public async Task<IActionResult> Create([FromBody] CreateCharacterRequest req)
    {
        if (string.IsNullOrWhiteSpace(req.Name))
            return BadRequest("Name required");

        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrWhiteSpace(userId))
            return Unauthorized();

        var character = new Character
        {
            OwnerUserId = userId,
            Name = req.Name.Trim(),
            CreatedUtc = DateTime.UtcNow
        };

        await _characters.CreateAsync(character);
        return Ok(character);
    }

    [HttpGet]
    [Authorize(Roles = "USER,SUPER")]
    public async Task<IActionResult> ListMine()
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrWhiteSpace(userId))
            return Unauthorized();

        var characters = await _characters.GetForOwnerAsync(userId);
        return Ok(characters);
    }

    [HttpDelete("{id}")]
    [Authorize(Roles = "USER,SUPER")]
    public async Task<IActionResult> Delete(string id)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrWhiteSpace(userId))
            return Unauthorized();

        var allowAnyOwner = User.IsInRole("SUPER");
        var deleted = await _characters.DeleteForOwnerAsync(id, userId, allowAnyOwner);
        if (!deleted)
            return NotFound();

        return Ok("Deleted");
    }
}
