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

namespace TaxBaik.Web.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class CompanyController(CompanyService companyService) : ControllerBase
{
    [HttpGet("{id:int}")]
    public async Task<IActionResult> GetById(int id)
    {
        try
        {
            var company = await companyService.GetByIdAsync(id);
            if (company == null)
                return NotFound(new ProblemDetails { Title = "회사를 찾을 수 없습니다.", Status = StatusCodes.Status404NotFound });
            return Ok(company);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new ProblemDetails { Title = "회사 조회 실패", Detail = ex.Message, Status = StatusCodes.Status500InternalServerError });
        }
    }

    [HttpGet("code/{code}")]
    public async Task<IActionResult> GetByCode(string code)
    {
        try
        {
            var company = await companyService.GetByCodeAsync(code);
            if (company == null)
                return NotFound(new ProblemDetails { Title = "회사를 찾을 수 없습니다.", Status = StatusCodes.Status404NotFound });
            return Ok(company);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new ProblemDetails { Title = "회사 조회 실패", Detail = ex.Message, Status = StatusCodes.Status500InternalServerError });
        }
    }

    [HttpGet]
    public async Task<IActionResult> GetPaged([FromQuery] int page = 1, [FromQuery] int pageSize = 20)
    {
        try
        {
            var (companies, total) = await companyService.GetPagedAsync(page, pageSize);
            return Ok(new { data = companies, total, page, pageSize });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new ProblemDetails { Title = "회사 목록 조회 실패", Detail = ex.Message, Status = StatusCodes.Status500InternalServerError });
        }
    }

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateCompanyRequest request)
    {
        try
        {
            var id = await companyService.CreateAsync(
                request.CompanyCode, request.CompanyName, request.ContactPerson,
                request.Phone, request.Email, request.Memo);
            return CreatedAtAction(nameof(GetById), new { id }, new { message = "회사가 등록되었습니다.", id });
        }
        catch (ValidationException ex)
        {
            return BadRequest(new ProblemDetails { Title = ex.Message, Status = StatusCodes.Status400BadRequest });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new ProblemDetails { Title = "회사 등록 실패", Detail = ex.Message, Status = StatusCodes.Status500InternalServerError });
        }
    }

    [HttpPut("{id:int}")]
    public async Task<IActionResult> Update(int id, [FromBody] UpdateCompanyRequest request)
    {
        try
        {
            await companyService.UpdateAsync(id, request.CompanyCode, request.CompanyName,
                request.ContactPerson, request.Phone, request.Email, request.Memo, request.IsActive);
            return Ok(new { message = "회사가 수정되었습니다." });
        }
        catch (ValidationException ex)
        {
            return BadRequest(new ProblemDetails { Title = ex.Message, Status = StatusCodes.Status400BadRequest });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new ProblemDetails { Title = "회사 수정 실패", Detail = ex.Message, Status = StatusCodes.Status500InternalServerError });
        }
    }

    [HttpDelete("{id:int}")]
    public async Task<IActionResult> Delete(int id)
    {
        try
        {
            await companyService.DeleteAsync(id);
            return Ok(new { message = "회사가 삭제되었습니다." });
        }
        catch (ValidationException ex)
        {
            return BadRequest(new ProblemDetails { Title = ex.Message, Status = StatusCodes.Status400BadRequest });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new ProblemDetails { Title = "회사 삭제 실패", Detail = ex.Message, Status = StatusCodes.Status500InternalServerError });
        }
    }

    public record CreateCompanyRequest(string CompanyCode, string CompanyName, string? ContactPerson, string? Phone, string? Email, string? Memo);
    public record UpdateCompanyRequest(string CompanyCode, string CompanyName, string? ContactPerson, string? Phone, string? Email, string? Memo, bool IsActive);
}
