package app

import (
	"encoding/json"

	"github.com/vstockwell/wraith/internal/settings"
)

type WorkspaceSnapshot struct {
	Tabs         []WorkspaceTab `json:"tabs"`
	SidebarWidth int            `json:"sidebarWidth"`
	SidebarMode  string         `json:"sidebarMode"`
	ActiveTab    int            `json:"activeTab"`
}

type WorkspaceTab struct {
	ConnectionID int64  `json:"connectionId"`
	Protocol     string `json:"protocol"`
	Position     int    `json:"position"`
}

type WorkspaceService struct {
	settings *settings.SettingsService
}

func NewWorkspaceService(s *settings.SettingsService) *WorkspaceService {
	return &WorkspaceService{settings: s}
}

// Save serializes the workspace snapshot to settings
func (w *WorkspaceService) Save(snapshot *WorkspaceSnapshot) error {
	data, err := json.Marshal(snapshot)
	if err != nil {
		return err
	}
	return w.settings.Set("workspace_snapshot", string(data))
}

// Load reads the last saved workspace snapshot
func (w *WorkspaceService) Load() (*WorkspaceSnapshot, error) {
	data, err := w.settings.Get("workspace_snapshot")
	if err != nil || data == "" {
		return nil, nil // no saved workspace
	}
	var snapshot WorkspaceSnapshot
	if err := json.Unmarshal([]byte(data), &snapshot); err != nil {
		return nil, err
	}
	return &snapshot, nil
}

// MarkCleanShutdown saves a flag indicating clean exit
func (w *WorkspaceService) MarkCleanShutdown() error {
	return w.settings.Set("clean_shutdown", "true")
}

// WasCleanShutdown checks if last exit was clean
func (w *WorkspaceService) WasCleanShutdown() bool {
	val, _ := w.settings.Get("clean_shutdown")
	return val == "true"
}

// ClearCleanShutdown removes the clean shutdown flag (called on startup)
func (w *WorkspaceService) ClearCleanShutdown() error {
	return w.settings.Delete("clean_shutdown")
}
