using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TaxBaik.Application.DTOs;
using TaxBaik.Application.Services;

namespace TaxBaik.Web.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AnnouncementController : ControllerBase
{
    private readonly AnnouncementService _announcementService;

    public AnnouncementController(AnnouncementService announcementService)
    {
        _announcementService = announcementService;
    }

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

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

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

        return Ok(announcement);
    }

    [HttpPost]
    [Authorize]
    public async Task<IActionResult> Create([FromBody] AnnouncementDto dto)
    {
        try
        {
            var announcementId = await _announcementService.CreateAsync(dto);
            var result = await _announcementService.GetByIdAsync(announcementId);
            return CreatedAtAction(nameof(GetById), new { id = announcementId }, 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] AnnouncementDto dto)
    {
        dto.Id = id;
        try
        {
            await _announcementService.UpdateAsync(dto);
            var result = await _announcementService.GetByIdAsync(id);
            if (result == null)
                return NotFound(new ProblemDetails { Title = "공지사항을 찾을 수 없습니다.", 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 _announcementService.DeleteAsync(id);
        return NoContent();
    }
}
