-- Identitäten
CREATE TABLE identities (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

-- Stammdaten (Key-Value)
CREATE TABLE identity_fields (
    id INT AUTO_INCREMENT PRIMARY KEY,
    identity_id INT NOT NULL,
    typ ENUM('single','multi','file') NULL,
    field_key VARCHAR(50) NOT NULL,
    field_value TEXT NOT NULL,
    FOREIGN KEY (identity_id)
        REFERENCES identities(id)
        ON DELETE CASCADE
) ENGINE=InnoDB;

-- Zugriffstoken (UUIDs)
CREATE TABLE access_tokens (
    id INT AUTO_INCREMENT PRIMARY KEY,
    identity_id INT NOT NULL,
    uuid CHAR(36) NOT NULL UNIQUE,
    expires_at DATETIME NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    notes TEXT NULL,
    FOREIGN KEY (identity_id)
        REFERENCES identities(id)
        ON DELETE CASCADE
) ENGINE=InnoDB;

-- Feldrechte pro Token
CREATE TABLE token_permissions (
    token_id INT NOT NULL,
    field_key VARCHAR(50) NOT NULL,
    PRIMARY KEY (token_id, field_key),
    FOREIGN KEY (token_id)
        REFERENCES access_tokens(id)
        ON DELETE CASCADE
) ENGINE=InnoDB;

-- Dateien (Bilder, PDFs, etc.)
CREATE TABLE files (
    id INT AUTO_INCREMENT PRIMARY KEY,
    identity_id INT NOT NULL,
    token_id INT NULL,
    filename VARCHAR(255) NOT NULL,
    stored_name VARCHAR(255) NOT NULL,
    mime_type VARCHAR(100),
    uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (identity_id)
        REFERENCES identities(id)
        ON DELETE CASCADE,
    FOREIGN KEY (token_id)
        REFERENCES access_tokens(id)
        ON DELETE SET NULL
) ENGINE=InnoDB;

CREATE TABLE admin_login_attempts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    ip_address VARCHAR(45) NOT NULL,
    attempts INT NOT NULL DEFAULT 1,
    locked_until DATETIME NULL,
    last_attempt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY (ip_address)
);

