using IWS5.Core.DTO;
using IWS5.DatabaseAccess.Interfaces.Importer;
using IWS5.DatabaseAccess.IwsDataContext;
using Microsoft.EntityFrameworkCore;

namespace IWS5.DatabaseAccess.Repositories.Importer;

public class ProcessRepository(IDbContextFactory<GreenfieldPd2015Context> contextFactory)
    : IProcessRepository
{
    public async Task<List<ProcessDto>> GetProcessesAsync()
    {
        await using var context = await contextFactory.CreateDbContextAsync();

        return await context.AtprocessDefinitions
                         .Select(p => new ProcessDto
                         {
                             ProcessName = p.ProcessName,
                             ProcessID = p.ProcessId,
                             ProcessVersion = p.ProcessVersion,
                             DefaultDocTemplate = p.DefaultDocTemplate,
                             Status = p.Status
                         })
                         .ToListAsync();
    }

    public async Task<ProcessDto?> GetProcessByNameAndVersionAsync(string processName, int? version = null)
    {
        await using var context = await contextFactory.CreateDbContextAsync();
        var query = context.AtprocessDefinitions
            .Where(p => p.ProcessName == processName);

        if (version.HasValue)
        {
            return await query
                .Where(p => p.ProcessVersion == version.Value)
                .Select(p => new ProcessDto
                {
                    ProcessName = p.ProcessName,
                    ProcessID = p.ProcessId,
                    ProcessVersion = p.ProcessVersion,
                    DefaultDocTemplate = p.DefaultDocTemplate,
                    Status = p.Status
                })
                .FirstOrDefaultAsync();
        }
        else
        {
            return await query
                .OrderByDescending(p => p.ProcessVersion)
                .Select(p => new ProcessDto
                {
                    ProcessName = p.ProcessName,
                    ProcessID = p.ProcessId,
                    ProcessVersion = p.ProcessVersion,
                    DefaultDocTemplate = p.DefaultDocTemplate,
                    Status = p.Status
                })
                .FirstOrDefaultAsync();
        }
    }
}
