-- ============================================================
-- YaoAI Comic Studio — M0 初始化表结构
-- ============================================================

-- 租户表
CREATE TABLE IF NOT EXISTS tenants
(
    id          BIGINT UNSIGNED  NOT NULL COMMENT '租户 ID（ULID 编码为 BIGINT）',
    name        VARCHAR(100)     NOT NULL COMMENT '租户名称',
    slug        VARCHAR(50)      NOT NULL COMMENT '唯一标识（URL 友好）',
    plan        VARCHAR(20)      NOT NULL DEFAULT 'free' COMMENT '套餐: free/pro/enterprise',
    status      TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态: 1=正常 0=禁用',
    credits     DECIMAL(18, 4)   NOT NULL DEFAULT 0 COMMENT '可用积分余额',
    frozen_credits DECIMAL(18, 4) NOT NULL DEFAULT 0 COMMENT '冻结积分（任务进行中）',
    created_at  DATETIME(3)      NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    updated_at  DATETIME(3)      NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
    deleted_at  DATETIME(3)               DEFAULT NULL COMMENT '逻辑删除时间',
    PRIMARY KEY (id),
    UNIQUE KEY uk_slug (slug),
    KEY idx_status (status),
    KEY idx_created_at (created_at)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT '租户表';

-- 用户表
CREATE TABLE IF NOT EXISTS users
(
    id          BIGINT UNSIGNED  NOT NULL COMMENT '用户 ID',
    tenant_id   BIGINT UNSIGNED  NOT NULL COMMENT '所属租户 ID',
    username    VARCHAR(50)      NOT NULL COMMENT '用户名',
    email       VARCHAR(100)     NOT NULL COMMENT '邮箱',
    phone       VARCHAR(20)               DEFAULT NULL COMMENT '手机号',
    avatar_url  VARCHAR(500)              DEFAULT NULL COMMENT '头像 URL',
    password_hash VARCHAR(255)   NOT NULL COMMENT 'BCrypt 哈希',
    role        VARCHAR(20)      NOT NULL DEFAULT 'member' COMMENT '平台角色: admin/member',
    status      TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态: 1=正常 0=禁用',
    last_login_at DATETIME(3)             DEFAULT NULL,
    created_at  DATETIME(3)      NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    updated_at  DATETIME(3)      NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
    deleted_at  DATETIME(3)               DEFAULT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uk_email (email),
    UNIQUE KEY uk_username_tenant (username, tenant_id),
    KEY idx_tenant_id (tenant_id),
    KEY idx_status (status)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT '用户表';

-- 租户成员关联表（多租户支持：一个用户可属于多个租户）
CREATE TABLE IF NOT EXISTS tenant_members
(
    id          BIGINT UNSIGNED  NOT NULL,
    tenant_id   BIGINT UNSIGNED  NOT NULL,
    user_id     BIGINT UNSIGNED  NOT NULL,
    role        VARCHAR(20)      NOT NULL DEFAULT 'member' COMMENT '租户内角色: owner/admin/member',
    joined_at   DATETIME(3)      NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    PRIMARY KEY (id),
    UNIQUE KEY uk_tenant_user (tenant_id, user_id),
    KEY idx_user_id (user_id)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci COMMENT '租户成员表';
