using Asp.Versioning; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Mirea.Api.DataAccess.Application.Cqrs.Group.Queries.GetGroupDetails; using Mirea.Api.DataAccess.Application.Cqrs.Group.Queries.GetGroupList; using Mirea.Api.Dto.Responses; using Mirea.Api.Endpoint.Common.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Mirea.Api.Endpoint.Controllers.V1; [ApiVersion("1.0")] [CacheMaxAge(true)] public class GroupController(IMediator mediator) : BaseController { private static int GetCourseNumber(string groupName) { var current = DateTime.Now; if (!int.TryParse(groupName[2..], out var yearOfGroup) && !int.TryParse(groupName.Split('-')[^1][..2], out yearOfGroup)) return -1; // Convert a two-digit year to a four-digit one yearOfGroup += current.Year / 100 * 100; return current.Year - yearOfGroup + (current.Month < 8 ? 0 : 1); } /// /// Retrieves a list of groups. /// /// The page number for pagination (optional). /// The page size for pagination (optional). /// A list of groups. [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] [BadRequestResponse] public async Task>> Get([FromQuery] int? page, [FromQuery] int? pageSize) { var result = await mediator.Send(new GetGroupListQuery() { Page = page, PageSize = pageSize }); return Ok(result.Groups .Select(g => new GroupResponse() { Id = g.Id, Name = g.Name, FacultyId = g.FacultyId, CourseNumber = GetCourseNumber(g.Name) }) ); } /// /// Retrieves detailed information about a specific group. /// /// The ID of the group to retrieve. /// Detailed information about the group. [HttpGet("{id:int}")] [ProducesResponseType(StatusCodes.Status200OK)] [BadRequestResponse] [NotFoundResponse] public async Task> GetDetails(int id) { var result = await mediator.Send(new GetGroupInfoQuery() { Id = id }); return Ok(new GroupDetailsResponse() { Id = result.Id, Name = result.Name, FacultyId = result.FacultyId, FacultyName = result.Faculty, CourseNumber = GetCourseNumber(result.Name) }); } /// /// Retrieves a list of groups by faculty ID. /// /// The ID of the faculty. /// A list of groups belonging to the specified faculty. [HttpGet("GetByFaculty/{id:int}")] [ProducesResponseType(StatusCodes.Status200OK)] [BadRequestResponse] [NotFoundResponse] public async Task>> GetByFaculty(int id) { var result = await mediator.Send(new GetGroupListQuery()); return Ok(result.Groups .Where(g => g.FacultyId == id) .Select(g => new GroupResponse() { Id = g.Id, Name = g.Name, CourseNumber = GetCourseNumber(g.Name), FacultyId = g.FacultyId })); } }