// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using FloraMultiPlatformFrontend.Application.Configuration;
using FloraMultiPlatformFrontend.Application.Services;
using FloraMultiPlatformFrontend.Application.Services.Interfaces;
using FloraMultiPlatformFrontend.Data.Entities;
using FloraMultiPlatformFrontend.Presentation.Models;
using Microsoft.EntityFrameworkCore;

namespace FloraMultiPlatformFrontend.Data;

public class FloraDbContext : DbContext
{
    private readonly IConfigurationService _configurationService;

    public FloraDbContext(DbContextOptions<FloraDbContext> options, IConfigurationService configurationService)
        : base(options)
    {
        _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));
    }

    public DbSet<AverageTag> AverageTags { get; set; } = null!;
    public DbSet<AdvanceRing> AdvanceRings { get; set; } = null!;
    public DbSet<AValueData> TagValues { get; set; } = null!;
    public DbSet<AdvanceTime> AdvanceTimes { get; set; } = null!;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        // Get the machine code from the currently selected machine
        var selectedMachine = _configurationService.GetSelectedMachineAsync().GetAwaiter().GetResult();
        var machineCode = selectedMachine?.Code ?? "DEFAULT";

        modelBuilder.Entity<AverageTag>()
            .ToTable($"AverageTags_{machineCode}");

        modelBuilder.Entity<AdvanceRing>()
            .ToTable($"AdvanceRings_{machineCode}");

        modelBuilder.Entity<AValueData>()
            .ToTable($"AValueData_{machineCode}");

        modelBuilder.Entity<AdvanceTime>()
            .ToTable($"AdvanceTimes_{machineCode}");

        modelBuilder.Entity<StateErrorRawResult>().HasNoKey();
    }
}
