CREATE TABLE IF NOT EXISTS upstreams (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL UNIQUE,
    type TEXT CHECK(type IN ('http', 'github', 'sourceforge')) NOT NULL,
    url TEXT,          -- Base URL ou GitHub repo ou flux RSS
    pattern TEXT DEFAULT NULL,      -- Regex pour HTTP ou pattern GitHub si besoin
    file TEXT,         -- Optionnel : fichier final ex: gcc-${version}.tar.xz
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS versions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    upstream_id INTEGER NOT NULL,
    version TEXT,
    url TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (upstream_id) REFERENCES upstreams(id)
);

CREATE TABLE IF NOT EXISTS packages (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT UNIQUE,
    upstream_id INTEGER,
    current_version_id INTEGER,
    FOREIGN KEY (upstream_id) REFERENCES upstreams(id),
    FOREIGN KEY (current_version_id) REFERENCES versions(id)
);

CREATE TABLE IF NOT EXISTS depends (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    package_id INTEGER NOT NULL,
    depends_on INTEGER NOT NULL,
    type TEXT CHECK(type IN ('runtime', 'build', 'check')),
    FOREIGN KEY (package_id) REFERENCES packages(id),
    FOREIGN KEY (depends_on) REFERENCES packages(id)
);

CREATE TABLE IF NOT EXISTS builds (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    package_id INTEGER NOT NULL,
    version TEXT NOT NULL,
    revision TEXT NOT NULL,
    status TEXT CHECK(status IN ('success', 'fail', 'pending')),
    built_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    log_path TEXT,
    FOREIGN KEY (package_id) REFERENCES packages(id)
);

CREATE TABLE IF NOT EXISTS repo (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    package_id INTEGER NOT NULL,
    version TEXT NOT NULL,
    path TEXT,
    added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (package_id) REFERENCES packages(id)
);
                    
CREATE TABLE IF NOT EXISTS notifications (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    version TEXT NOT NULL,
    url TEXT NOT NULL,
    status TEXT DEFAULT 'pending', -- 'pending', 'sent', 'failed'
    last_attempt TIMESTAMP,        -- Pour savoir quand on a tenté la dernière fois
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
                    
CREATE UNIQUE INDEX idx_upstream_version ON versions(upstream_id, version);