package sqlite

import (
	"context"
	"database/sql"
)

type PolicyStore struct{ db *sql.DB }

func NewPolicyStore(db *sql.DB) *PolicyStore { return &PolicyStore{db: db} }

func (s *PolicyStore) GetBool(ctx context.Context, key string) (bool, error) {
	var val string
	err := s.db.QueryRowContext(ctx, `SELECT value FROM platform_policies WHERE key = ?`, key).Scan(&val)
	if err != nil {
		return false, err
	}
	return val == "true", nil
}

func (s *PolicyStore) SetBool(ctx context.Context, key string, val bool) error {
	v := "false"
	if val {
		v = "true"
	}
	return s.Set(ctx, key, v)
}

func (s *PolicyStore) Get(ctx context.Context, key string) (string, error) {
	var val string
	err := s.db.QueryRowContext(ctx, `SELECT value FROM platform_policies WHERE key = ?`, key).Scan(&val)
	if err != nil {
		return "", err
	}
	return val, nil
}

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

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