using FluentValidation;
using IWS5.Core.DTO.IAdmin.Reports;
using IWS5.Core.Helpers;
using IWS5.DatabaseAccess.Interfaces.IAdmin;

namespace IWS5.Services.Validators.IAdmin.Reports;

public class CreateReportRequestValidator : AbstractValidator<CreateReportRequestDTO>
{
    public CreateReportRequestValidator(IReportRepository reportRepository)
    {
        RuleFor(x => x.Name)
            .NotEmpty().WithMessage("Report name is required.")
            .MaximumLength(50).WithMessage("Report name must not exceed 50 characters.")
            .Must(name => reportRepository.GetByNameAsync(name).Result == null)
            .WithMessage("Report name must be unique.");

        RuleFor(x => x.Description)
            .MaximumLength(255)
            .WithMessage("Description must not exceed 255 characters.");

        RuleFor(x => x.SqlCode)
            .NotEmpty().WithMessage("SQL code is required.")
            .MaximumLength(1024).WithMessage("SQL code must not exceed 1024 characters.")
            .Must(sql => sql.TrimStart().StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
            .WithMessage("SQL code must start with a SELECT statement.")
            .Must(sql => !SqlValidatorHelper.ContainsForbiddenKeywords(sql))
            .WithMessage("SQL code contains forbidden statements (INSERT, UPDATE, DELETE, DROP, EXEC, etc.).")
            .Must(sql => SqlValidatorHelper.IsSafeSqlSyntax(sql))
            .WithMessage("SQL code appears to be malformed or unsafe.");
    }
}
