using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MilitaryTrainingManagement.Data;
using MilitaryTrainingManagement.Models.DTOs;
using MilitaryTrainingManagement.Models.Entities;
using MilitaryTrainingManagement.Services.Interfaces;

namespace MilitaryTrainingManagement.Controllers;

/// <summary>
/// 物资类别管理控制器
/// </summary>
[Authorize]
public class MaterialCategoriesController : BaseApiController
{
    private readonly ApplicationDbContext _context;
    private readonly IAuditService _auditService;

    public MaterialCategoriesController(ApplicationDbContext context, IAuditService auditService)
    {
        _context = context;
        _auditService = auditService;
    }
    
    private string? GetClientIpAddress()
    {
        return HttpContext.Connection.RemoteIpAddress?.ToString();
    }

    /// <summary>
    /// 获取所有物资类别
    /// </summary>
    [HttpGet]
    public async Task<IActionResult> GetAll([FromQuery] bool? activeOnly = true)
    {
        var query = _context.MaterialCategories.AsQueryable();
        
        if (activeOnly == true)
        {
            query = query.Where(c => c.IsActive);
        }
        
        var categories = await query
            .OrderBy(c => c.SortOrder)
            .ThenBy(c => c.Name)
            .ToListAsync();
            
        return Ok(categories);
    }

    /// <summary>
    /// 根据ID获取物资类别
    /// </summary>
    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(int id)
    {
        var category = await _context.MaterialCategories.FindAsync(id);
        if (category == null)
        {
            return NotFound(new { message = "物资类别不存在" });
        }
        return Ok(category);
    }

    /// <summary>
    /// 创建物资类别
    /// </summary>
    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateMaterialCategoryRequest request)
    {
        var unitId = GetCurrentUnitId();
        var userId = GetCurrentUserId();
        
        // 检查名称是否已存在
        var exists = await _context.MaterialCategories
            .AnyAsync(c => c.Name == request.Name);
        if (exists)
        {
            return BadRequest(new { message = "物资类别名称已存在" });
        }

        var category = new MaterialCategory
        {
            Name = request.Name,
            Description = request.Description,
            SortOrder = request.SortOrder,
            IsActive = true,
            CreatedAt = DateTime.UtcNow
        };

        _context.MaterialCategories.Add(category);
        await _context.SaveChangesAsync();

        // 记录审计日志
        await _auditService.LogApprovalAsync(
            "MaterialCategory",
            category.Id,
            "Create",
            $"创建物资类别：{request.Name}",
            userId,
            unitId,
            GetClientIpAddress());

        return CreatedAtAction(nameof(GetById), new { id = category.Id }, category);
    }

    /// <summary>
    /// 更新物资类别
    /// </summary>
    [HttpPut("{id}")]
    public async Task<IActionResult> Update(int id, [FromBody] UpdateMaterialCategoryRequest request)
    {
        var unitId = GetCurrentUnitId();
        var userId = GetCurrentUserId();
        
        var category = await _context.MaterialCategories.FindAsync(id);
        if (category == null)
        {
            return NotFound(new { message = "物资类别不存在" });
        }

        // 检查名称是否与其他类别重复
        var exists = await _context.MaterialCategories
            .AnyAsync(c => c.Name == request.Name && c.Id != id);
        if (exists)
        {
            return BadRequest(new { message = "物资类别名称已存在" });
        }

        category.Name = request.Name;
        category.Description = request.Description;
        category.SortOrder = request.SortOrder;
        category.IsActive = request.IsActive;

        await _context.SaveChangesAsync();

        // 记录审计日志
        await _auditService.LogApprovalAsync(
            "MaterialCategory",
            id,
            "Update",
            $"更新物资类别：{request.Name}",
            userId,
            unitId,
            GetClientIpAddress());

        return Ok(category);
    }

    /// <summary>
    /// 删除物资类别
    /// </summary>
    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        var unitId = GetCurrentUnitId();
        var userId = GetCurrentUserId();
        
        var category = await _context.MaterialCategories.FindAsync(id);
        if (category == null)
        {
            return NotFound(new { message = "物资类别不存在" });
        }

        // 检查是否有配额使用此类别
        var hasAllocations = await _context.MaterialAllocations
            .AnyAsync(a => a.Category == category.Name);
        if (hasAllocations)
        {
            return BadRequest(new { message = "该类别已被使用，无法删除" });
        }

        var categoryName = category.Name;
        _context.MaterialCategories.Remove(category);
        await _context.SaveChangesAsync();

        // 记录审计日志
        await _auditService.LogApprovalAsync(
            "MaterialCategory",
            id,
            "Delete",
            $"删除物资类别：{categoryName}",
            userId,
            unitId,
            GetClientIpAddress());        return Ok(new { message = "删除成功" });
    }
}
