CREATE TABLE MembershipPlan (
    id VARCHAR(191) NOT NULL, name VARCHAR(100) NOT NULL, description VARCHAR(500),
    price DOUBLE NOT NULL DEFAULT 0, currency VARCHAR(8) NOT NULL DEFAULT 'CNY',
    aiCallLimit INT NOT NULL DEFAULT 100, storageLimit INT NOT NULL DEFAULT 0,
    ocrLimit INT NOT NULL DEFAULT 0, visionLimit INT NOT NULL DEFAULT 0,
    embeddingLimit INT NOT NULL DEFAULT 0, active BOOLEAN NOT NULL DEFAULT true,
    createdAt DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    updatedAt DATETIME(3) NOT NULL, PRIMARY KEY (id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

CREATE TABLE UserMembership (
    id VARCHAR(191) NOT NULL, userId VARCHAR(191) NOT NULL, planId VARCHAR(191) NOT NULL,
    startedAt DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), expiresAt DATETIME(3),
    autoRenew BOOLEAN NOT NULL DEFAULT false, active BOOLEAN NOT NULL DEFAULT true,
    createdAt DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    updatedAt DATETIME(3) NOT NULL,
    INDEX UserMembership_userId_idx(userId),
    PRIMARY KEY (id),
    CONSTRAINT UserMembership_planId_fkey FOREIGN KEY (planId) REFERENCES MembershipPlan(id) ON DELETE RESTRICT ON UPDATE CASCADE,
    CONSTRAINT UserMembership_userId_fkey FOREIGN KEY (userId) REFERENCES User(id) ON DELETE RESTRICT ON UPDATE CASCADE
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

CREATE TABLE QuotaUsage (
    id VARCHAR(191) NOT NULL, userId VARCHAR(191) NOT NULL,
    quotaType VARCHAR(32) NOT NULL, amount INT NOT NULL, resource VARCHAR(255),
    createdAt DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    INDEX QuotaUsage_userId_quotaType_idx(userId, quotaType),
    INDEX QuotaUsage_createdAt_idx(createdAt), PRIMARY KEY (id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

CREATE TABLE CostDailySummary (
    id VARCHAR(191) NOT NULL, date DATETIME(3) NOT NULL,
    provider VARCHAR(32) NOT NULL, model VARCHAR(100),
    calls INT NOT NULL DEFAULT 0, tokens INT NOT NULL DEFAULT 0, cost DOUBLE NOT NULL DEFAULT 0,
    createdAt DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    UNIQUE INDEX CostDailySummary_date_provider_model_key(date, provider, model),
    PRIMARY KEY (id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
