using FlatRender.ContentSvc.Application.Services;
using FlatRender.ContentSvc.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace FlatRender.ContentSvc.Controllers;

[ApiController]
[Route("v1/preset-stories")]
public class PresetStoriesController(PresetStoryService svc) : ControllerBase
{
    // Anonymous + non-admin callers only see published stories; admins see drafts too.
    private bool IsAdmin => User.IsInRole("Admin");

    [HttpGet]
    public async Task<IActionResult> List([FromQuery(Name = "project_id")] Guid projectId) =>
        Ok(await svc.GetByProjectAsync(projectId, publishedOnly: !IsAdmin));

    [HttpGet("{id:guid}")]
    public async Task<IActionResult> Get(Guid id)
    {
        var s = await svc.GetAsync(id, publishedOnly: !IsAdmin);
        return s == null ? NotFound() : Ok(s);
    }

    [Authorize(Roles = "Admin")]
    [HttpPost]
    public async Task<IActionResult> Create([FromBody] SavePresetStoryRequest req) =>
        Ok(await svc.CreateAsync(req));

    [Authorize(Roles = "Admin")]
    [HttpPut("{id:guid}")]
    public async Task<IActionResult> Update(Guid id, [FromBody] SavePresetStoryRequest req) =>
        Ok(await svc.UpdateAsync(id, req));

    [Authorize(Roles = "Admin")]
    [HttpDelete("{id:guid}")]
    public async Task<IActionResult> Delete(Guid id)
    {
        await svc.DeleteAsync(id);
        return NoContent();
    }
}
