using Microsoft.EntityFrameworkCore;
using UniVerse.Application.DTOs.Reviews;
using UniVerse.Application.Interfaces;
using UniVerse.Application.Prompts;
using UniVerse.Domain.Entities;
using UniVerse.Domain.Exceptions;
using UniVerse.Infrastructure.Data;

namespace UniVerse.Infrastructure.Services;

public class ReviewPromptService : IReviewPromptService
{
    private readonly AppDbContext _db;

    public ReviewPromptService(AppDbContext db)
    {
        _db = db;
    }

    public async Task<ReviewPromptDto> GetAsync()
    {
        var setting = await _db.ReviewPromptSettings
            .AsNoTracking()
            .FirstOrDefaultAsync(s => s.Id == ReviewPromptSetting.SingletonId);

        return setting is null
            ? new ReviewPromptDto(ReviewPromptTemplate.Default, null)
            : new ReviewPromptDto(setting.Prompt, setting.UpdatedAt);
    }

    public async Task<ReviewPromptDto> UpdateAsync(UpdateReviewPromptRequest request)
    {
        ValidatePrompt(request.Prompt);

        var now = DateTime.UtcNow;
        var setting = await _db.ReviewPromptSettings
            .FirstOrDefaultAsync(s => s.Id == ReviewPromptSetting.SingletonId);

        if (setting is null)
        {
            setting = new ReviewPromptSetting
            {
                Id = ReviewPromptSetting.SingletonId,
                Prompt = request.Prompt,
                CreatedAt = now,
                UpdatedAt = now
            };
            _db.ReviewPromptSettings.Add(setting);
        }
        else
        {
            setting.Prompt = request.Prompt;
            setting.UpdatedAt = now;
        }

        await _db.SaveChangesAsync();

        return new ReviewPromptDto(setting.Prompt, setting.UpdatedAt);
    }

    private static void ValidatePrompt(string prompt)
    {
        if (string.IsNullOrWhiteSpace(prompt))
            throw new BadRequestException("Prompt must not be empty.");

        if (!ReviewPromptTemplate.HasRequiredPlaceholders(prompt))
            throw new BadRequestException(
                $"Prompt must contain {ReviewPromptTemplate.LectureContextPlaceholder} and {ReviewPromptTemplate.ReviewTextPlaceholder} placeholders.");
    }
}
