package db

import "fmt"

// FirewallRule is a database firewall rule record.
type FirewallRule struct {
	ID    int64
	Type  string // "ip", "cidr", "country"
	Value string
}

// ListFirewallRules returns all firewall rules.
func (s *Store) ListFirewallRules() ([]FirewallRule, error) {
	rows, err := s.db.Query("SELECT id, type, value FROM firewall_rules ORDER BY type, value")
	if err != nil {
		return nil, fmt.Errorf("querying firewall rules: %w", err)
	}
	defer rows.Close()

	var rules []FirewallRule
	for rows.Next() {
		var r FirewallRule
		if err := rows.Scan(&r.ID, &r.Type, &r.Value); err != nil {
			return nil, fmt.Errorf("scanning firewall rule: %w", err)
		}
		rules = append(rules, r)
	}
	return rules, rows.Err()
}

// CreateFirewallRule inserts a firewall rule and returns its ID.
func (s *Store) CreateFirewallRule(ruleType, value string) (int64, error) {
	result, err := s.db.Exec(
		"INSERT INTO firewall_rules (type, value) VALUES (?, ?)",
		ruleType, value,
	)
	if err != nil {
		return 0, fmt.Errorf("inserting firewall rule: %w", err)
	}
	return result.LastInsertId()
}

// DeleteFirewallRule deletes a firewall rule by type and value.
func (s *Store) DeleteFirewallRule(ruleType, value string) error {
	result, err := s.db.Exec(
		"DELETE FROM firewall_rules WHERE type = ? AND value = ?",
		ruleType, value,
	)
	if err != nil {
		return fmt.Errorf("deleting firewall rule: %w", err)
	}
	n, _ := result.RowsAffected()
	if n == 0 {
		return fmt.Errorf("firewall rule (%s, %s) not found", ruleType, value)
	}
	return nil
}
