// Package db defines the database schema.
package db

// CurrentSchemaVersion returns the current schema version (for migrations)
func CurrentSchemaVersion() int {
	return 1
}

// CreateTableStatements returns a list of CREATE TABLE statements.
func CreateTableStatements() []string {
	return []string{
		createNodesTable(),
		createAttributesTable(),
		createNetworksTable(),
		createSubnetsTable(),
		createSoftwareTable(),
	}
}

// DropTableOrder returns table names in reverse dependency order for safe DROP.
func DropTableOrder() []string {
	return []string{"software", "attributes", "nodes", "subnets", "networks"}
}

// --- Private DDL Functions ---

func createNodesTable() string {
	return `
CREATE TABLE IF NOT EXISTS nodes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    hostname TEXT NOT NULL UNIQUE,
    ip TEXT,
    status TEXT DEFAULT 'active',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);`
}

func createAttributesTable() string {
	return `
CREATE TABLE IF NOT EXISTS attributes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    node_id INTEGER NOT NULL,
    key TEXT NOT NULL,
    value TEXT NOT NULL,
    FOREIGN KEY(node_id) REFERENCES nodes(id) ON DELETE CASCADE,
    UNIQUE(node_id, key)
);`
}

func createNetworksTable() string {
	return `
CREATE TABLE IF NOT EXISTS networks (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL UNIQUE,
    description TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);`
}

func createSubnetsTable() string {
	return `
CREATE TABLE IF NOT EXISTS subnets (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    network_id INTEGER NOT NULL,
    cidr TEXT NOT NULL,
    gateway TEXT,
    vlan INTEGER,
    FOREIGN KEY(network_id) REFERENCES networks(id) ON DELETE CASCADE,
    UNIQUE(network_id, cidr)
);`
}

func createSoftwareTable() string {
	return `
CREATE TABLE IF NOT EXISTS software (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    version TEXT NOT NULL,
    installed_on INTEGER,
    FOREIGN KEY(installed_on) REFERENCES nodes(id) ON DELETE SET NULL,
    UNIQUE(name, version, installed_on)
);`
}
