package browser

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"sync"
)

// TabStorage manages persistent storage of tab IDs
type TabStorage struct {
	Tabs map[string]string // Maps tab IDs to their internal IDs
	mu   sync.Mutex
}

// NewTabStorage creates a new tab storage
func NewTabStorage() (*TabStorage, error) {
	storage := &TabStorage{
		Tabs: make(map[string]string),
	}

	// Load existing tabs from storage
	err := storage.load()
	if err != nil {
		// If the file doesn't exist, that's fine - we'll create it
		if !os.IsNotExist(err) {
			return nil, fmt.Errorf("failed to load tab storage: %w", err)
		}
	}

	return storage, nil
}

// SaveTab saves a tab ID to storage
func (s *TabStorage) SaveTab(tabID string) error {
	s.mu.Lock()
	defer s.mu.Unlock()

	s.Tabs[tabID] = tabID
	return s.save()
}

// GetTab gets a tab ID from storage
func (s *TabStorage) GetTab(tabID string) (string, bool) {
	s.mu.Lock()
	defer s.mu.Unlock()

	internalID, exists := s.Tabs[tabID]
	return internalID, exists
}

// RemoveTab removes a tab ID from storage
func (s *TabStorage) RemoveTab(tabID string) error {
	s.mu.Lock()
	defer s.mu.Unlock()

	delete(s.Tabs, tabID)
	return s.save()
}

// getStoragePath returns the path to the storage file
func getStoragePath() (string, error) {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		return "", fmt.Errorf("failed to get user home directory: %w", err)
	}

	// Create .cremote directory if it doesn't exist
	storageDir := filepath.Join(homeDir, ".cremote")
	err = os.MkdirAll(storageDir, 0755)
	if err != nil {
		return "", fmt.Errorf("failed to create storage directory: %w", err)
	}

	return filepath.Join(storageDir, "tabs.json"), nil
}

// load loads the tab storage from disk
func (s *TabStorage) load() error {
	path, err := getStoragePath()
	if err != nil {
		return err
	}

	data, err := os.ReadFile(path)
	if err != nil {
		return err
	}

	return json.Unmarshal(data, &s.Tabs)
}

// save saves the tab storage to disk
func (s *TabStorage) save() error {
	path, err := getStoragePath()
	if err != nil {
		return err
	}

	data, err := json.MarshalIndent(s.Tabs, "", "  ")
	if err != nil {
		return fmt.Errorf("failed to marshal tab storage: %w", err)
	}

	return os.WriteFile(path, data, 0644)
}
