-- MarkBase Authentication Database Schema
-- Synced from SFTPGo PostgreSQL

-- 1. Users table (synced from sftpgo.users)
CREATE TABLE IF NOT EXISTS sftpgo_users (
    username TEXT PRIMARY KEY,
    password_hash TEXT NOT NULL,
    email TEXT,
    status INTEGER DEFAULT 1,
    home_dir TEXT,
    permissions TEXT,
    uid INTEGER,
    gid INTEGER,
    last_login INTEGER,
    created_at INTEGER,
    updated_at INTEGER,
    last_sync_at INTEGER,
    sync_status INTEGER DEFAULT 0
);

CREATE INDEX IF NOT EXISTS idx_users_status ON sftpgo_users(status);
CREATE INDEX IF NOT EXISTS idx_users_sync_status ON sftpgo_users(sync_status);

-- 2. Groups table (synced from sftpgo.groups)
CREATE TABLE IF NOT EXISTS sftpgo_groups (
    name TEXT PRIMARY KEY,
    description TEXT,
    created_at INTEGER,
    updated_at INTEGER,
    last_sync_at INTEGER
);

-- 3. Users-Groups mapping (synced from sftpgo.users_groups_mapping)
CREATE TABLE IF NOT EXISTS users_groups_mapping (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT NOT NULL,
    group_name TEXT NOT NULL,
    created_at INTEGER,
    FOREIGN KEY (username) REFERENCES sftpgo_users(username) ON DELETE CASCADE,
    FOREIGN KEY (group_name) REFERENCES sftpgo_groups(name) ON DELETE CASCADE,
    UNIQUE(username, group_name)
);

CREATE INDEX IF NOT EXISTS idx_mapping_username ON users_groups_mapping(username);
CREATE INDEX IF NOT EXISTS idx_mapping_group ON users_groups_mapping(group_name);

-- 4. Sync log table
CREATE TABLE IF NOT EXISTS sync_log (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    sync_type TEXT,
    sync_time INTEGER,
    users_synced INTEGER DEFAULT 0,
    users_failed INTEGER DEFAULT 0,
    groups_synced INTEGER DEFAULT 0,
    groups_failed INTEGER DEFAULT 0,
    mappings_synced INTEGER DEFAULT 0,
    mappings_failed INTEGER DEFAULT 0,
    admins_synced INTEGER DEFAULT 0,
    admins_failed INTEGER DEFAULT 0,
    status TEXT,
    error_message TEXT,
    details TEXT
);

CREATE INDEX IF NOT EXISTS idx_sync_time ON sync_log(sync_time);
CREATE INDEX IF NOT EXISTS idx_sync_status ON sync_log(status);

-- 5. Admins table (synced from sftpgo.admins)
CREATE TABLE IF NOT EXISTS sftpgo_admins (
    username TEXT PRIMARY KEY,
    password_hash TEXT NOT NULL,
    email TEXT,
    description TEXT,
    status INTEGER DEFAULT 1,
    permissions TEXT NOT NULL,
    filters TEXT,
    role_id INTEGER,
    last_login INTEGER DEFAULT 0,
    created_at INTEGER NOT NULL,
    updated_at INTEGER NOT NULL,
    last_sync_at INTEGER
);

CREATE INDEX IF NOT EXISTS idx_admins_status ON sftpgo_admins(status);
