namespace WebApi.Controllers;

[ApiController]
[Route("api/[controller]/[action]")]
public class TransactionCategoryController(
    ITransactionCategoryRepository categoryRepository,
    ITransactionRecordRepository transactionRecordRepository,
    ILogger<TransactionCategoryController> logger,
    IBudgetRepository budgetRepository
) : ControllerBase
{
    /// <summary>
    /// 获取分类列表（支持按类型筛选）
    /// </summary>
    [HttpGet]
    public async Task<BaseResponse<List<TransactionCategory>>> GetListAsync([FromQuery] TransactionType? type = null)
    {
        try
        {
            List<TransactionCategory> categories;
            if (type.HasValue)
            {
                categories = await categoryRepository.GetCategoriesByTypeAsync(type.Value);
            }
            else
            {
                categories = (await categoryRepository.GetAllAsync()).ToList();
            }
            
            return categories.Ok();
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "获取分类列表失败");
            return $"获取分类列表失败: {ex.Message}".Fail<List<TransactionCategory>>();
        }
    }

    /// <summary>
    /// 根据ID获取分类详情
    /// </summary>
    [HttpGet("{id}")]
    public async Task<BaseResponse<TransactionCategory>> GetByIdAsync(long id)
    {
        try
        {
            var category = await categoryRepository.GetByIdAsync(id);
            if (category == null)
            {
                return "分类不存在".Fail<TransactionCategory>();
            }

            return category.Ok();
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "获取分类详情失败, Id: {Id}", id);
            return $"获取分类详情失败: {ex.Message}".Fail<TransactionCategory>();
        }
    }

    /// <summary>
    /// 创建分类
    /// </summary>
    [HttpPost]
    public async Task<BaseResponse<long>> CreateAsync([FromBody] CreateCategoryDto dto)
    {
        try
        {
            // 检查同名分类
            var existing = await categoryRepository.GetByNameAndTypeAsync(dto.Name, dto.Type);
            if (existing != null)
            {
                return "已存在相同名称的分类".Fail<long>();
            }

            var category = new TransactionCategory
            {
                Name = dto.Name,
                Type = dto.Type
            };

            var result = await categoryRepository.AddAsync(category);
            if (result)
            {
                return category.Id.Ok();
            }
            else
            {
                return "创建分类失败".Fail<long>();
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "创建分类失败, Dto: {@Dto}", dto);
            return $"创建分类失败: {ex.Message}".Fail<long>();
        }
    }

    /// <summary>
    /// 更新分类
    /// </summary>
    [HttpPost]
    public async Task<BaseResponse> UpdateAsync([FromBody] UpdateCategoryDto dto)
    {
        try
        {
            var category = await categoryRepository.GetByIdAsync(dto.Id);
            if (category == null)
            {
                return "分类不存在".Fail();
            }

            // 如果修改了名称，检查同名
            if (category.Name != dto.Name)
            {
                var existing = await categoryRepository.GetByNameAndTypeAsync(dto.Name, category.Type);
                if (existing != null && existing.Id != dto.Id)
                {
                    return "已存在相同名称的分类".Fail();
                }

                // 同步更新交易记录中的分类名称
                await transactionRecordRepository.UpdateCategoryNameAsync(category.Name, dto.Name, category.Type);
                await budgetRepository.UpdateBudgetCategoryNameAsync(category.Name, dto.Name, category.Type);
            }

            category.Name = dto.Name;
            category.UpdateTime = DateTime.Now;

            var success = await categoryRepository.UpdateAsync(category);
            if (success)
            {
                return "更新分类成功".Ok();
            }
            else
            {
                return "更新分类失败".Fail();
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "更新分类失败, Dto: {@Dto}", dto);
            return $"更新分类失败: {ex.Message}".Fail();
        }
    }

    /// <summary>
    /// 删除分类
    /// </summary>
    [HttpPost]
    public async Task<BaseResponse> DeleteAsync([FromQuery] long id)
    {
        try
        {
            // 检查是否被使用
            var inUse = await categoryRepository.IsCategoryInUseAsync(id);
            if (inUse)
            {
                return "该分类已被使用，无法删除".Fail();
            }

            var success = await categoryRepository.DeleteAsync(id);
            if (success)
            {
                return BaseResponse.Done();
            }
            else
            {
                return "删除分类失败，分类不存在".Fail();
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "删除分类失败, Id: {Id}", id);
            return $"删除分类失败: {ex.Message}".Fail();
        }
    }

    /// <summary>
    /// 批量创建分类（用于初始化）
    /// </summary>
    [HttpPost]
    public async Task<BaseResponse<int>> BatchCreateAsync([FromBody] List<CreateCategoryDto> dtoList)
    {
        try
        {
            var categories = dtoList.Select(dto => new TransactionCategory
            {
                Name = dto.Name,
                Type = dto.Type
            }).ToList();

            var result = await categoryRepository.AddRangeAsync(categories);
            if (result)
            {
                return categories.Count.Ok();
            }
            else
            {
                return "批量创建分类失败".Fail<int>();
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "批量创建分类失败, Count: {Count}", dtoList.Count);
            return $"批量创建分类失败: {ex.Message}".Fail<int>();
        }
    }
}

/// <summary>
/// 创建分类DTO
/// </summary>
public record CreateCategoryDto(
    string Name,
    TransactionType Type
);

/// <summary>
/// 更新分类DTO
/// </summary>
public record UpdateCategoryDto(
    long Id,
    string Name
);
