-- ─── Tenants ──────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS tenants (
    id              CHAR(36) NOT NULL DEFAULT (UUID()),
    name            VARCHAR(255) NOT NULL,
    email           VARCHAR(255) NOT NULL,
    phone           VARCHAR(20) NULL,
    status          ENUM('active','suspended','trial') NOT NULL DEFAULT 'trial',
    trial_ends_at   DATETIME NULL,
    settings        JSON DEFAULT (JSON_OBJECT()),
    created_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    deleted_at      DATETIME NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uq_tenants_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ─── Users ────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS users (
    id                  CHAR(36) NOT NULL DEFAULT (UUID()),
    tenant_id           CHAR(36) NOT NULL,
    name                VARCHAR(255) NOT NULL,
    email               VARCHAR(255) NOT NULL,
    password_hash       VARCHAR(255) NOT NULL,
    role                ENUM('super_admin','admin','accountant','employee','viewer') NOT NULL,
    assigned_company_id CHAR(36) NULL,
    refresh_token_hash  VARCHAR(255) NULL,
    totp_secret         VARCHAR(64) NULL,
    totp_enabled        TINYINT(1) NOT NULL DEFAULT 0,
    is_active           TINYINT(1) NOT NULL DEFAULT 1,
    email_verified_at   DATETIME NULL,
    last_login_at       DATETIME NULL,
    last_login_ip       VARCHAR(45) NULL,
    failed_login_count  INT NOT NULL DEFAULT 0,
    locked_until        DATETIME NULL,
    created_at          DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at          DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    deleted_at          DATETIME NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uq_tenant_email (tenant_id, email),
    CONSTRAINT fk_users_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
