using IWS5.DatabaseAccess.Interfaces.IAdmin;
using IWS5.DatabaseAccess.IwsDataContext;
using IWS5.DatabaseAccess.IwsDataModels;
using Microsoft.EntityFrameworkCore;

namespace IWS5.DatabaseAccess.Repositories.IAdmin;

public class ScheduleTaskRepository(GreenfieldPd2015Context context)
    : IWSRepository<AtscheduledTask>(context), IScheduleTaskRepository
{
    public async Task<List<AtscheduledTask>> ListByScheduleAsync(int scheduleId)
    {
        return await context.AtscheduledTasks
            .Include(t => t.TaskType)
            .Where(t => t.ScheduleId == scheduleId)
            .OrderBy(t => t.SortOrder)
            .ToListAsync();
    }

    public async Task<AtscheduledTask?> GetByIdAsync(int taskId)
    {
        return await context.AtscheduledTasks
            .Include(t => t.TaskType)
            .FirstOrDefaultAsync(t => t.TaskId == taskId);
    }

    public async Task AddAsync(AtscheduledTask entity)
    {
        context.AtscheduledTasks.Add(entity);
        await context.SaveChangesAsync();
    }

    public async Task UpdateAsync(AtscheduledTask entity)
    {
        context.AtscheduledTasks.Update(entity);
        await context.SaveChangesAsync();
    }

    public async Task DeleteAsync(AtscheduledTask entity)
    {
        context.AtscheduledTasks.Remove(entity);
        await context.SaveChangesAsync();
    }

    public async Task<bool> RunTaskAsync(int taskId)
    {
        var task = await context.AtscheduledTasks.FirstOrDefaultAsync(t => t.TaskId == taskId);
        if (task == null) return false;

        // TODO: Placeholder for real task execution logic
        return true;
    }

    public async Task<List<AttaskType>> ListTaskTypesAsync()
        => await context.AttaskTypes.OrderBy(t => t.TaskTypeId).ToListAsync();

    public async Task<AttaskType?> GetTaskTypeByIdAsync(int taskTypeId)
        => await context.AttaskTypes.FirstOrDefaultAsync(t => t.TaskTypeId == taskTypeId);

    public async Task<List<AttaskActionType>> ListTaskActionTypesAsync()
    => await context.AttaskActionTypes
        .OrderBy(x => x.ActionId)
        .ToListAsync();

    public async Task<AttaskActionType?> GetTaskActionTypeByIdAsync(int actionId)
        => await context.AttaskActionTypes
            .FirstOrDefaultAsync(x => x.ActionId == actionId);
}
