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

namespace TaxBaik.Web.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class TaxFilingController : ControllerBase
{
    private readonly TaxFilingService _taxFilingService;

    public TaxFilingController(TaxFilingService taxFilingService)
    {
        _taxFilingService = taxFilingService;
    }

    [HttpGet("upcoming")]
    public async Task<IActionResult> GetUpcoming([FromQuery] int daysAhead = 30)
    {
        var filings = await _taxFilingService.GetUpcomingAsync(daysAhead);
        return Ok(new { data = filings });
    }

    [HttpGet("client/{clientId}")]
    public async Task<IActionResult> GetByClientId(int clientId)
    {
        var filings = await _taxFilingService.GetByClientIdAsync(clientId);
        return Ok(new { data = filings });
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(int id)
    {
        var filing = await _taxFilingService.GetByIdAsync(id);
        if (filing == null)
            return NotFound(new ProblemDetails { Title = "신고 일정을 찾을 수 없습니다.", Status = StatusCodes.Status404NotFound });

        return Ok(filing);
    }

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

    [HttpPut("{id}")]
    public async Task<IActionResult> Update(int id, [FromBody] TaxFiling filing)
    {
        filing.Id = id;
        try
        {
            await _taxFilingService.UpdateAsync(filing);
            var result = await _taxFilingService.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}")]
    public async Task<IActionResult> Delete(int id)
    {
        await _taxFilingService.DeleteAsync(id);
        return NoContent();
    }
}
