CREATE DATABASE IF NOT EXISTS market;
USE market;
CREATE TABLE IF NOT EXISTS users(
    sqlId INT PRIMARY KEY AUTO INCREMENT,
    userId VARCHAR(36) UNIQUE NOT NULL,
    userName VARCHAR(64) UNIQUE NOT NULL,
    passwordHash VARCHAR(64) NOT NULL,
    email VARCHAR(64) UNIQUE NOT NULL,
    balance FLOAT NOT NULL DEFAULT 0,
    publicKey VARCHAR(128) NOT NULL
);
CREATE TABLE IF NOT EXISTS buy_orders(
    sqlId INT PRIMARY KEY AUTO INCREMENT,
    buyOrderId VARCHAR(36) UNIQUE NOT NULL,
    timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP(),
    expires DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP() + INTERVAL 3 DAY,
    pageId INT NOT NULL,
    price FLOAT NOT NULL,
    volume INT NOT NULL,
    fee FLOAT NOT NULL DEFAULT 0,
    sold INT NOT NULL DEFAULT 0,
    FOREIGN KEY (userId) REFERENCES users(userId)
);
CREATE TABLE IF NOT EXISTS sell_orders(
    sqlId INT PRIMARY KEY AUTO INCREMENT,
    sellOrderId VARCHAR(36) UNIQUE NOT NULL,
    timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP(),
    expires DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP() + INTERVAL 3 DAY,
    price FLOAT NOT NULL,
    fee FLOAT NOT NULL,
    FOREIGN KEY (userId) REFERENCES users(userId)
);
CREATE TABLE IF NOT EXISTS sell_orders_items(
    sqlId INT PRIMARY KEY AUTO INCREMENT,
    cardId VARCHAR(36) NOT NULL,
    FOREIGN KEY (sellOrderId) REFERENCES sell_orders(sellOrderId) NOT NULL
);
CREATE TABLE IF NOT EXISTS transactions(
    sqlId INT PRIMARY KEY AUTO INCREMENT,
    transactionId VARCHAR(36) UNIQUE NOT NULL,
    isPending BOOLEAN NOT NULL DEFAULT true,
    isAbandoned BOOLEAN NOT NULL DEFAULT false,
    FOREIGN KEY (buyOrderId) REFERENCES buy_orders(buyOrderId) NOT NULL,
    FOREIGN KEY (sellOrderItemSqlId) REFERENCES sell_order_items(sqlId) NOT NULL
);
