using RobotNet.Script.Shares;
using RobotNet.ScriptManager.Data;

namespace RobotNet.ScriptManager.Services;

public class ScriptMissionCreator(ScriptMissionManager missionManager, ScriptManagerDbContext scriptManagerDb)
{
    public async Task<Guid> CreateMissionAsync(string name, IDictionary<string, string> parameters)
    {
        if (!missionManager.ContainsMissionName(name)) 
            throw new Exception($"Mission {name} không tồn tại");

        var entry = scriptManagerDb.InstanceMissions.Add(new InstanceMission
        {
            MissionName = name,
            Parameters = System.Text.Json.JsonSerializer.Serialize(parameters),
            CreatedAt = DateTime.UtcNow,
            Status = MissionStatus.Idle,
        });

        await scriptManagerDb.SaveChangesAsync();

        try
        {
            missionManager.Create(entry.Entity.Id, name, parameters);
            return entry.Entity.Id;
        }
        catch (Exception ex)
        {
            scriptManagerDb.InstanceMissions.Remove(entry.Entity);
            await scriptManagerDb.SaveChangesAsync();
            throw new Exception($"Failed to create mission: {ex.Message}", ex);
        }
    }

    public async Task<Guid> CreateMissionAsync(string name, object[] parameters)
    {
        if (!missionManager.ContainsMissionName(name))
            throw new Exception($"Mission {name} không tồn tại");

        var entry = scriptManagerDb.InstanceMissions.Add(new InstanceMission
        {
            MissionName = name,
            Parameters = System.Text.Json.JsonSerializer.Serialize(parameters),
            CreatedAt = DateTime.UtcNow,
            Status = MissionStatus.Idle,
        });

        await scriptManagerDb.SaveChangesAsync();

        try
        {
            missionManager.Create(entry.Entity.Id, name, parameters);
            return entry.Entity.Id;
        }
        catch (Exception ex)
        {
            scriptManagerDb.InstanceMissions.Remove(entry.Entity);
            await scriptManagerDb.SaveChangesAsync();
            throw new Exception($"Failed to create mission: {ex.Message}", ex);
        }
    }
}
