CREATE DATABASE IF NOT EXISTS sakurupiah_wallet_demo CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE sakurupiah_wallet_demo;

CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(120) NOT NULL,
    email VARCHAR(120) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    balance DECIMAL(18,2) NOT NULL DEFAULT 0,
    role ENUM('user','admin') NOT NULL DEFAULT 'user',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    setting_key VARCHAR(100) NOT NULL UNIQUE,
    setting_value TEXT NULL,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS topup_transactions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    merchant_ref VARCHAR(100) NOT NULL UNIQUE,
    trx_id VARCHAR(120) NULL,
    payment_code VARCHAR(50) NULL,
    payment_name VARCHAR(100) NULL,
    amount DECIMAL(18,2) NOT NULL DEFAULT 0,
    internal_fee DECIMAL(18,2) NOT NULL DEFAULT 0,
    total_bill DECIMAL(18,2) NOT NULL DEFAULT 0,
    sakurupiah_fee_mode TINYINT NOT NULL DEFAULT 2,
    payment_no VARCHAR(120) NULL,
    checkout_url TEXT NULL,
    qr_string LONGTEXT NULL,
    expired_at DATETIME NULL,
    paid_at DATETIME NULL,
    status VARCHAR(30) NOT NULL DEFAULT 'pending',
    raw_request LONGTEXT NULL,
    raw_response LONGTEXT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_topup_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS wallet_transactions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    topup_id INT NULL,
    type ENUM('credit','debit') NOT NULL,
    amount DECIMAL(18,2) NOT NULL DEFAULT 0,
    description VARCHAR(255) NULL,
    status VARCHAR(30) NOT NULL DEFAULT 'success',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_wallet_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    CONSTRAINT fk_wallet_topup FOREIGN KEY (topup_id) REFERENCES topup_transactions(id) ON DELETE SET NULL
) ENGINE=InnoDB;
