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

namespace LocationsApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class LocationsController : ControllerBase
{
    private readonly LocationStore _locations;

    public LocationsController(LocationStore locations)
    {
        _locations = locations;
    }

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

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

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

        await _locations.CreateAsync(location);
        return Ok(location);
    }

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

        var locations = await _locations.GetForOwnerAsync(userId);
        return Ok(locations);
    }

    [HttpDelete("{id}")]
    [Authorize(Roles = "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 _locations.DeleteForOwnerAsync(id, userId, allowAnyOwner);
        if (!deleted)
            return NotFound();

        return Ok("Deleted");
    }

    [HttpPut("{id}")]
    [Authorize(Roles = "SUPER")]
    public async Task<IActionResult> Update(string id, [FromBody] UpdateLocationRequest req)
    {
        if (string.IsNullOrWhiteSpace(req.Name))
            return BadRequest("Name required");

        var updated = await _locations.UpdateNameAsync(id, req.Name.Trim());
        if (!updated)
            return NotFound();

        return Ok("Updated");
    }
}
