using Microsoft.EntityFrameworkCore;
using NetworkResurrector.Api.Domain.Data.DbContexts;
using NetworkResurrector.Api.Domain.Entities;
using NetworkResurrector.Api.Domain.Entities.Power;
using NetworkResurrector.Api.Domain.Repositories;
using System;
using System.Threading.Tasks;

namespace NetworkResurrector.Api.Domain.Data.Repositories
{
    class NetworkRepository : INetworkRepository
    {
        private readonly NetworkDbContext _dbContext;

        public NetworkRepository(NetworkDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public Task<Machine[]> GetMachines()
        {
            return _dbContext.Machines.ToArrayAsync();
        }

        public async Task<Machine> GetMachine(int machineId)
        {
            var machine = await _dbContext.Machines
                .Include(z => z.Agent)
                .FirstOrDefaultAsync(z => z.MachineId == machineId);
            if (machine == null)
                throw new Exception($"Machine with id {machineId} not found");

            return machine;
        }

        public async Task<PowerActionConfiguration> GetPowerActionConfiguration(int machineId, string actionCode)
        {
            var config = await _dbContext.PowerActionConfigurations
                .Include(z => z.PowerAction)
                .Include(z => z.Performer)
                .FirstOrDefaultAsync(z => z.MachineId == machineId && z.PowerAction.PowerActionCode == actionCode);

            if (config == null)
                throw new Exception($"Action '{actionCode}' is not configured for machine '{machineId}'.");

            return config;
        }

        public async Task<PowerActionConfiguration> GetPowerActionConfiguration(int machineId, int actionId)
        {
            var config = await _dbContext.PowerActionConfigurations
                .Include(z => z.PowerAction)
                .Include(z => z.Performer)
                .FirstOrDefaultAsync(z => z.MachineId == machineId && z.PowerActionId == actionId);

            if (config == null)
                throw new Exception($"Action '{actionId}' is not configured for machine '{machineId}'.");

            return config;
        }
    }
}
