using System.Text.Json;

namespace OrderPROPrint.Models;

public class AppSettings
{
    public string ApiUrl { get; set; } = "";
    public string ApiKey { get; set; } = "";
    public string PrinterName { get; set; } = "";
    public int PollIntervalSeconds { get; set; } = 10;

    private static string SettingsDir =>
        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "OrderPROPrint");

    private static string SettingsPath =>
        Path.Combine(SettingsDir, "settings.json");

    public bool IsConfigured =>
        !string.IsNullOrWhiteSpace(ApiUrl) && !string.IsNullOrWhiteSpace(ApiKey) && !string.IsNullOrWhiteSpace(PrinterName);

    public static AppSettings Load()
    {
        try
        {
            if (File.Exists(SettingsPath))
            {
                var json = File.ReadAllText(SettingsPath);
                return JsonSerializer.Deserialize<AppSettings>(json) ?? new AppSettings();
            }
        }
        catch
        {
            // Return defaults on any error
        }

        return new AppSettings();
    }

    public void Save()
    {
        Directory.CreateDirectory(SettingsDir);
        var json = JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true });
        File.WriteAllText(SettingsPath, json);
    }
}
