using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SurveyBackend.Core.Contexts;
using SurveyBackend.DTOs.Survey;
using SurveyBackend.Mappers;
using SurveyBackend.Services.Exceptions;
using SurveyLib.Core.Models;
using SurveyLib.Core.Services;
namespace SurveyBackend.Controllers;
///
[ApiController]
[Route("api/surveys")]
public class SurveyController : ControllerBase
{
private readonly ISurveyService _surveyService;
private readonly IUserContext _userContext;
///
public SurveyController(ISurveyService surveyService, IUserContext userContext)
{
_surveyService = surveyService;
_userContext = userContext;
}
///
/// Получить ВСЕ опросы
///
/// Возвращает массив вообще всех опросов
///
[AllowAnonymous]
[HttpGet]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
public async Task Get()
{
var surveys = await _surveyService.GetSurveysAsync();
var result = surveys.Select(SurveyMapper.ModelToOutputDto);
return Ok(result);
}
///
/// Получить опрос по ID
///
/// А что тут говорить то
///
///
[AllowAnonymous]
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(OutputSurveyDto), StatusCodes.Status200OK)]
public async Task Get(int id)
{
var survey = await _surveyService.GetSurveyAsync(id);
var result = SurveyMapper.ModelToOutputDto(survey);
return Ok(result);
}
///
/// Добавить новый опрос
///
///
///
///
[Authorize]
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task Post([FromBody] CreateSurveyDto dto)
{
var userId = _userContext.UserId;
var survey = SurveyMapper.CreateDtoToModel(dto, userId);
await _surveyService.AddSurveyAsync(survey);
var result = SurveyMapper.ModelToOutputDto(survey);
return Ok(result);
}
///
/// Обновляет опрос целиком
///
///
///
///
[Authorize]
[HttpPut("{id}")]
public async Task Put(int id, [FromBody] UpdateSurveyDto dto)
{
var userId = _userContext.UserId;
var survey = SurveyMapper.UpdateDtoToModel(dto, userId, id);
await _surveyService.UpdateSurveyAsync(survey);
var result = SurveyMapper.ModelToOutputDto(survey);
return Ok(result);
}
///
/// Удалить опрос по ID
///
/// Опрос должен быть создан тобой чтоб его удалить
///
///
[Authorize]
[HttpDelete("{id}")]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task Delete(int id)
{
await _surveyService.DeleteSurveyAsync(id);
return Ok();
}
///
/// Получить МОИ опроса
///
/// Возвращает только опросы созданные нынешним юзером
///
[Authorize]
[HttpGet("my")]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
public async Task GetMySurveys()
{
var userId = _userContext.UserId;
var result = await _surveyService.GetSurveysByUserIdAsync(userId);
return Ok(result);
}
}