using IWS5.Core.Enums;
using IWS5.DatabaseAccess.Interfaces;
using IWS5.DatabaseAccess.IwsDataContext;
using IWS5.DatabaseAccess.IwsDataModels;
using Microsoft.EntityFrameworkCore;
using Serilog;

namespace IWS5.DatabaseAccess.Repositories;

public class TriggerDefinitionRepository(GreenfieldPd2015Context context, ILogger logger)  : IWSRepository<AteventTriggerDefinition>(context), ITriggerDefinitionRepository
{

    public async Task<List<AteventTriggerDefinition>> ListTriggerDefinitionsByWorkItemIdAsync(int workItemId, 
        ATTriggerHook? hook = null,
        ATTriggerAction? action = null)
    {
        logger.Information(
            "Entering ListTriggerDefinitionsByWorkItemIdAsync - WorkItemId: {WorkItemId}, Hook: {Hook}, Action: {Action}",
            workItemId, hook?.ToString() ?? "null", action?.ToString() ?? "null");

        try
        {
            var eventTriggerDefQuery = context.AtworkItemReferences
                .AsNoTracking()
                .Where(wir => wir.WorkItemId == workItemId)
                .SelectMany(wir => wir.Event.AteventTriggerTemplates)
                .SelectMany(ett => ett.Template.AteventTriggerDefinitions);

            if (hook.HasValue)
            {
                logger.Information("Applying Hook filter: {Hook}", hook.Value, hook.Value);
                eventTriggerDefQuery = eventTriggerDefQuery.Where(etd => etd.HookId == (int)hook.Value);
            }
            
            if (action.HasValue)
            {
                logger.Information("Applying Action filter: {Action}", action.Value, action.Value);
                eventTriggerDefQuery = eventTriggerDefQuery.Where(etd => etd.ActionId == (int)action.Value);
            }
            
            var queryText = eventTriggerDefQuery.ToQueryString();
            logger.Information("Generated SQL Query: {QueryText}", queryText);
            
            logger.Information("Executing query to retrieve trigger definitions for WorkItemId: {WorkItemId}", workItemId);
            
            var data = await eventTriggerDefQuery.ToListAsync();
            
            if (data.Count == 0)
            {
                logger.Warning(
                    "No trigger definitions found for WorkItemId: {WorkItemId}, Hook: {Hook}, Action: {Action}",
                    workItemId, hook?.ToString() ?? "null", action?.ToString() ?? "null");
            }
            else
            {
                logger.Information(
                    "Successfully retrieved {Count} trigger definition(s) for WorkItemId: {WorkItemId}",
                    data.Count, workItemId);
            }

            return data;
        }
        catch (Exception ex)
        {
            logger.Error(ex, 
                "Error retrieving trigger definitions for WorkItemId: {WorkItemId}, Hook: {Hook}, Action: {Action}",
                workItemId, hook?.ToString() ?? "null", action?.ToString() ?? "null");
            throw;
        }
    }
}