-- File Share Database Schema
-- MariaDB 10.3+

CREATE DATABASE IF NOT EXISTS file_share
    CHARACTER SET utf8mb4
    COLLATE utf8mb4_unicode_ci;

USE file_share;

CREATE TABLE accounts (
    id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username      VARCHAR(128)  NOT NULL UNIQUE,
    api_key       VARCHAR(128)  NOT NULL UNIQUE,
    password_hash VARCHAR(255)  NOT NULL,
    role          VARCHAR(16)   NOT NULL DEFAULT 'user',
    created_at    TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE files (
    id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    account_id   BIGINT UNSIGNED NOT NULL,
    filename     VARCHAR(512)    NOT NULL,
    mime_type    VARCHAR(256)    NOT NULL,
    size         BIGINT UNSIGNED NOT NULL,
    sha256       CHAR(64)        NOT NULL,
    data         LONGBLOB        NOT NULL,
    uploaded_at  TIMESTAMP       NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (account_id) REFERENCES accounts (id) ON DELETE CASCADE,
    INDEX idx_account (account_id)
);

CREATE TABLE download_otp (
    id         BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    file_id    BIGINT UNSIGNED NOT NULL,
    code       CHAR(5)         NOT NULL,
    used       TINYINT(1)      NOT NULL DEFAULT 0,
    created_at TIMESTAMP      NOT NULL DEFAULT CURRENT_TIMESTAMP,
    expires_at TIMESTAMP      NOT NULL,
    INDEX idx_code (code),
    INDEX idx_expires (expires_at),
    FOREIGN KEY (file_id) REFERENCES files (id) ON DELETE CASCADE
);

-- Seed data
INSERT INTO accounts (username, api_key, password_hash, role)
VALUES ('kamma', 'kamma-api-key-initial-2026', '$2a$10$fUslPcoWmwNyFLvY0pM5GONpdVa2XTALvJPybuIP/MEKccdndjQIq', 'admin');
