using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TaxBaik.Application.Services;
using TaxBaik.Domain.Entities;

namespace TaxBaik.Web.Controllers;

[ApiController]
[Route("api/[controller]")]
public class FaqController : ControllerBase
{
    private readonly FaqService _faqService;

    public FaqController(FaqService faqService)
    {
        _faqService = faqService;
    }

    [HttpGet("active")]
    public async Task<IActionResult> GetActive()
    {
        var faqs = await _faqService.GetActiveAsync();
        return Ok(new { data = faqs });
    }

    [HttpGet]
    [Authorize]
    public async Task<IActionResult> GetAll()
    {
        var faqs = await _faqService.GetAllAsync();
        return Ok(new { data = faqs });
    }

    [HttpGet("{id}")]
    [Authorize]
    public async Task<IActionResult> GetById(int id)
    {
        var faq = await _faqService.GetByIdAsync(id);
        if (faq == null)
            return NotFound(new ProblemDetails { Title = "FAQ를 찾을 수 없습니다.", Status = StatusCodes.Status404NotFound });

        return Ok(faq);
    }

    [HttpPost]
    [Authorize]
    public async Task<IActionResult> Create([FromBody] Faq faq)
    {
        try
        {
            var faqId = await _faqService.CreateAsync(faq);
            var result = await _faqService.GetByIdAsync(faqId);
            return CreatedAtAction(nameof(GetById), new { id = faqId }, result);
        }
        catch (Exception ex)
        {
            return BadRequest(new ProblemDetails { Title = ex.Message, Status = StatusCodes.Status400BadRequest });
        }
    }

    [HttpPut("{id}")]
    [Authorize]
    public async Task<IActionResult> Update(int id, [FromBody] Faq faq)
    {
        faq.Id = id;
        try
        {
            await _faqService.UpdateAsync(faq);
            var result = await _faqService.GetByIdAsync(id);
            if (result == null)
                return NotFound(new ProblemDetails { Title = "FAQ를 찾을 수 없습니다.", Status = StatusCodes.Status404NotFound });

            return Ok(result);
        }
        catch (Exception ex)
        {
            return BadRequest(new ProblemDetails { Title = ex.Message, Status = StatusCodes.Status400BadRequest });
        }
    }

    [HttpDelete("{id}")]
    [Authorize]
    public async Task<IActionResult> Delete(int id)
    {
        await _faqService.DeleteAsync(id);
        return NoContent();
    }
}
