using SurveyBackend.Core.Contexts; using SurveyBackend.Core.Repositories; using SurveyBackend.Services.Exceptions; using SurveyLib.Core.Models; using SurveyLib.Core.Repositories; using SurveyLib.Core.Services; namespace SurveyBackend.Services.Services; public class SurveyService : ISurveyService { private readonly ISurveyRepository _surveyRepository; private readonly IUserContext _userContext; public SurveyService(ISurveyRepository surveyRepository, IUserContext userContext) { _surveyRepository = surveyRepository; _userContext = userContext; } public async Task AddSurveyAsync(Survey survey) { await _surveyRepository.AddAsync(survey); } public async Task UpdateSurveyAsync(Survey survey) { if (survey.CreatedBy != _userContext.UserId) throw new UnauthorizedException("You are not authorized to update this survey."); await _surveyRepository.UpdateAsync(survey); } public async Task DeleteSurveyAsync(int id) { var survey = await _surveyRepository.GetByIdAsync(id); if (survey is null) { throw new NotFoundException("Survey not found"); } if (survey.CreatedBy != _userContext.UserId) { throw new UnauthorizedException("You are not authorized to delete this survey."); } await _surveyRepository.DeleteAsync(id); } public async Task> GetSurveysAsync() { return await _surveyRepository.GetAllAsync(); } public async Task GetSurveyAsync(int id) { var survey = await _surveyRepository.GetByIdAsync(id); if (survey is null) { throw new NotFoundException("Survey not found"); } return survey; } public async Task> GetSurveysByUserIdAsync(int userId) { return await _surveyRepository.GetSurveysByUserIdAsync(userId); } }