package sqlite

import (
	"context"
	"database/sql"

	"chat-switchboard/models"
)

type PolicyStore struct{}

func NewPolicyStore() *PolicyStore { return &PolicyStore{} }

func (s *PolicyStore) Get(ctx context.Context, key string) (string, error) {
	var value string
	err := DB.QueryRowContext(ctx,
		"SELECT value FROM platform_policies WHERE key = ?", key).Scan(&value)
	if err == sql.ErrNoRows {
		if def, ok := models.PolicyDefaults[key]; ok {
			return def, nil
		}
		return "", nil
	}
	return value, err
}

func (s *PolicyStore) GetBool(ctx context.Context, key string) (bool, error) {
	val, err := s.Get(ctx, key)
	if err != nil {
		return false, err
	}
	return val == "true", nil
}

func (s *PolicyStore) Set(ctx context.Context, key, value, updatedBy string) error {
	_, err := DB.ExecContext(ctx, `
		INSERT INTO platform_policies (key, value, updated_by, updated_at)
		VALUES (?, ?, ?, datetime('now'))
		ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_by = excluded.updated_by, updated_at = datetime('now')`,
		key, value, updatedBy, value, updatedBy)
	return err
}

func (s *PolicyStore) GetAll(ctx context.Context) (map[string]string, error) {
	result := make(map[string]string)
	for k, v := range models.PolicyDefaults {
		result[k] = v
	}
	rows, err := DB.QueryContext(ctx, "SELECT key, value FROM platform_policies")
	if err != nil {
		return result, err
	}
	defer rows.Close()
	for rows.Next() {
		var k, v string
		if err := rows.Scan(&k, &v); err != nil {
			continue
		}
		result[k] = v
	}
	return result, rows.Err()
}
