-- Initial schema for upaas

-- Users table (single admin user)
CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    username TEXT UNIQUE NOT NULL,
    password_hash TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Apps table
CREATE TABLE apps (
    id TEXT PRIMARY KEY,
    name TEXT UNIQUE NOT NULL,
    repo_url TEXT NOT NULL,
    branch TEXT NOT NULL DEFAULT 'main',
    dockerfile_path TEXT DEFAULT 'Dockerfile',
    webhook_secret TEXT NOT NULL,
    ssh_private_key TEXT NOT NULL,
    ssh_public_key TEXT NOT NULL,
    container_id TEXT,
    image_id TEXT,
    status TEXT DEFAULT 'pending',
    docker_network TEXT,
    ntfy_topic TEXT,
    slack_webhook TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- App environment variables
CREATE TABLE app_env_vars (
    id INTEGER PRIMARY KEY,
    app_id TEXT NOT NULL REFERENCES apps(id) ON DELETE CASCADE,
    key TEXT NOT NULL,
    value TEXT NOT NULL,
    UNIQUE(app_id, key)
);

-- App labels
CREATE TABLE app_labels (
    id INTEGER PRIMARY KEY,
    app_id TEXT NOT NULL REFERENCES apps(id) ON DELETE CASCADE,
    key TEXT NOT NULL,
    value TEXT NOT NULL,
    UNIQUE(app_id, key)
);

-- App volume mounts
CREATE TABLE app_volumes (
    id INTEGER PRIMARY KEY,
    app_id TEXT NOT NULL REFERENCES apps(id) ON DELETE CASCADE,
    host_path TEXT NOT NULL,
    container_path TEXT NOT NULL,
    readonly INTEGER DEFAULT 0
);

-- Webhook events log
CREATE TABLE webhook_events (
    id INTEGER PRIMARY KEY,
    app_id TEXT NOT NULL REFERENCES apps(id) ON DELETE CASCADE,
    event_type TEXT NOT NULL,
    branch TEXT NOT NULL,
    commit_sha TEXT,
    payload TEXT,
    matched INTEGER NOT NULL,
    processed INTEGER DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Deployments log
CREATE TABLE deployments (
    id INTEGER PRIMARY KEY,
    app_id TEXT NOT NULL REFERENCES apps(id) ON DELETE CASCADE,
    webhook_event_id INTEGER REFERENCES webhook_events(id),
    commit_sha TEXT,
    image_id TEXT,
    container_id TEXT,
    status TEXT NOT NULL,
    logs TEXT,
    started_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    finished_at DATETIME
);

-- Indexes
CREATE INDEX idx_apps_status ON apps(status);
CREATE INDEX idx_apps_webhook_secret ON apps(webhook_secret);
CREATE INDEX idx_app_env_vars_app_id ON app_env_vars(app_id);
CREATE INDEX idx_app_labels_app_id ON app_labels(app_id);
CREATE INDEX idx_app_volumes_app_id ON app_volumes(app_id);
CREATE INDEX idx_webhook_events_app_id ON webhook_events(app_id);
CREATE INDEX idx_webhook_events_created_at ON webhook_events(created_at);
CREATE INDEX idx_deployments_app_id ON deployments(app_id);
CREATE INDEX idx_deployments_started_at ON deployments(started_at);
