-- ============================================================
-- M14 平台运营后台
--   1) admin_users / admin_audit_logs / plans / tenant_quotas
--   2) tenants 加暂停元信息
--   3) billing_records 升级到模型粒度（核心）
--   4) 套餐初始化数据
-- ============================================================

-- ---------- 1) 运营人员 ----------
CREATE TABLE admin_users
(
    id                   BIGINT      NOT NULL,
    username             VARCHAR(64) NOT NULL,
    password_hash        VARCHAR(255)         DEFAULT NULL COMMENT 'BCrypt; 首启由 AdminInitializer 注入默认密码',
    display_name         VARCHAR(128)         DEFAULT NULL,
    email                VARCHAR(255)         DEFAULT NULL,
    role                 VARCHAR(32) NOT NULL DEFAULT 'OPERATOR' COMMENT 'SUPER_ADMIN/OPERATOR/FINANCE/READONLY',
    status               TINYINT     NOT NULL DEFAULT 1 COMMENT '1=ACTIVE 0=DISABLED',
    must_change_password TINYINT     NOT NULL DEFAULT 0,
    last_login_at        DATETIME(3)          DEFAULT NULL,
    last_login_ip        VARCHAR(45)          DEFAULT NULL,
    created_by           BIGINT               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),
    PRIMARY KEY (id),
    UNIQUE KEY uk_username (username),
    KEY idx_role_status (role, status)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT '运营人员';

-- ---------- 2) 运营操作审计 ----------
CREATE TABLE admin_audit_logs
(
    id             BIGINT      NOT NULL,
    admin_user_id  BIGINT      NOT NULL,
    admin_username VARCHAR(64)          DEFAULT NULL COMMENT '冗余字段，账号删除后仍可追溯',
    action         VARCHAR(64) NOT NULL COMMENT 'TENANT_RECHARGE/TENANT_SUSPEND/PLAN_CHANGE/USER_DISABLE/IMPERSONATE_START/...',
    resource_type  VARCHAR(32)          DEFAULT NULL,
    resource_id    VARCHAR(64)          DEFAULT NULL,
    before_value   JSON                 DEFAULT NULL,
    after_value    JSON                 DEFAULT NULL,
    ip             VARCHAR(45)          DEFAULT NULL,
    user_agent     VARCHAR(255)         DEFAULT NULL,
    request_id     VARCHAR(64)          DEFAULT NULL,
    status         VARCHAR(16) NOT NULL DEFAULT 'SUCCESS' COMMENT 'SUCCESS/FAILED',
    error_message  TEXT                 DEFAULT NULL,
    created_at     DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    PRIMARY KEY (id),
    KEY idx_admin_time (admin_user_id, created_at),
    KEY idx_resource (resource_type, resource_id),
    KEY idx_action_time (action, created_at)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT '运营操作审计';

-- ---------- 3) 套餐定义 ----------
CREATE TABLE plans
(
    id                   BIGINT      NOT NULL,
    code                 VARCHAR(32) NOT NULL COMMENT 'FREE/PRO/TEAM/ENTERPRISE',
    name                 VARCHAR(64) NOT NULL,
    price_monthly        DECIMAL(10, 2)       DEFAULT 0,
    monthly_credits      INT                  DEFAULT 0,
    max_members          INT                  DEFAULT 1 COMMENT '0=不限',
    max_projects         INT                  DEFAULT 0 COMMENT '0=不限',
    max_concurrent_tasks INT                  DEFAULT 1,
    features             JSON                 DEFAULT NULL,
    is_active            TINYINT     NOT NULL DEFAULT 1,
    updated_at           DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
    updated_by           BIGINT               DEFAULT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uk_code (code)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT '套餐定义';

-- ---------- 4) 租户配额覆盖 ----------
CREATE TABLE tenant_quotas
(
    tenant_id            BIGINT      NOT NULL,
    max_members          INT                  DEFAULT NULL,
    max_projects         INT                  DEFAULT NULL,
    max_monthly_credits  INT                  DEFAULT NULL,
    max_concurrent_tasks INT                  DEFAULT NULL,
    monthly_budget_limit DECIMAL(18, 4)       DEFAULT NULL,
    notes                TEXT                 DEFAULT NULL,
    updated_at           DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
    updated_by           BIGINT               DEFAULT NULL,
    PRIMARY KEY (tenant_id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT '租户配额覆盖';

-- ---------- 5) tenants 暂停元信息 ----------
ALTER TABLE tenants
    ADD COLUMN suspended_at     DATETIME(3)  DEFAULT NULL COMMENT '暂停时间',
    ADD COLUMN suspended_by     BIGINT       DEFAULT NULL COMMENT '操作人 admin_users.id',
    ADD COLUMN suspended_reason VARCHAR(255) DEFAULT NULL,
    ADD COLUMN notes            TEXT         DEFAULT NULL COMMENT '运营备注';

-- ---------- 6) billing_records 模型粒度升级（核心） ----------
ALTER TABLE billing_records
    ADD COLUMN created_by_admin_id BIGINT       DEFAULT NULL COMMENT '运营手动充值时记录',
    ADD COLUMN user_id             BIGINT       DEFAULT NULL COMMENT '租户内发起操作的用户',
    ADD COLUMN modality            VARCHAR(16)  DEFAULT NULL COMMENT 'TEXT/IMAGE/VIDEO/AUDIO/COMPOSE/RECHARGE',
    ADD COLUMN model_provider      VARCHAR(32)  DEFAULT NULL COMMENT 'volcengine/qwen/openai/ffmpeg',
    ADD COLUMN model_id            VARCHAR(64)  DEFAULT NULL,
    ADD COLUMN model_name          VARCHAR(128) DEFAULT NULL,
    ADD COLUMN unit_count          INT          DEFAULT 1,
    ADD COLUMN success             TINYINT(1)   DEFAULT 1,
    ADD COLUMN billing_meta        JSON         DEFAULT NULL,
    ADD INDEX idx_modality_model (modality, model_provider, model_id),
    ADD INDEX idx_user_created (user_id, created_at);

-- 把历史数据的 modality 推断填充（旧数据没有 modality 列，按 operation 反推）
UPDATE billing_records SET modality = 'TEXT'    WHERE modality IS NULL AND operation IN ('outline_generate', 'episode_generate');
UPDATE billing_records SET modality = 'IMAGE'   WHERE modality IS NULL AND operation = 'image_generate';
UPDATE billing_records SET modality = 'VIDEO'   WHERE modality IS NULL AND operation = 'video_generate';
UPDATE billing_records SET modality = 'COMPOSE' WHERE modality IS NULL AND operation = 'assembly';
UPDATE billing_records SET modality = 'RECHARGE' WHERE modality IS NULL AND operation = 'recharge';

-- ---------- 7) 套餐初始化数据（对齐 design-docs/01 §4.1） ----------
INSERT INTO plans (id, code, name, price_monthly, monthly_credits, max_members, max_projects, max_concurrent_tasks, features, is_active)
VALUES
    (1, 'FREE',       '免费版', 0.00,    100,   1,  3,   1, JSON_OBJECT('watermark', true,  'libraries', JSON_ARRAY('personal')), 1),
    (2, 'PRO',        '专业版', 99.00,   3000,  5,  20,  3, JSON_OBJECT('watermark', false, 'libraries', JSON_ARRAY('personal','team')), 1),
    (3, 'TEAM',       '团队版', 499.00,  20000, 20, 100, 5, JSON_OBJECT('watermark', false, 'libraries', JSON_ARRAY('personal','team'), 'api', true), 1),
    (4, 'ENTERPRISE', '企业版', 0.00,    0,     0,  0,  10, JSON_OBJECT('watermark', false, 'libraries', JSON_ARRAY('personal','team','market'), 'api', true, 'sla', true, 'private_deploy', true), 1);
