-- 宿主客户与 API Key（管理端动态签发，无需改 .env）
CREATE TABLE `host_customer` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    `customer_id` VARCHAR(32) NOT NULL,
    `name` VARCHAR(128) NOT NULL,
    `status` VARCHAR(16) NOT NULL DEFAULT 'active',
    `remark` VARCHAR(255) NULL,
    `is_deleted` BOOLEAN NOT NULL DEFAULT false,
    `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updated_at` DATETIME(3) NOT NULL,

    UNIQUE INDEX `host_customer_customer_id_key`(`customer_id`),
    INDEX `idx_host_customer_status`(`status`, `is_deleted`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

CREATE TABLE `service_api_key` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    `key_id` VARCHAR(32) NOT NULL,
    `customer_id` VARCHAR(32) NOT NULL,
    `token_hash` CHAR(64) NOT NULL,
    `key_prefix` VARCHAR(16) NOT NULL,
    `permissions` JSON NOT NULL,
    `is_active` BOOLEAN NOT NULL DEFAULT true,
    `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updated_at` DATETIME(3) NOT NULL,

    UNIQUE INDEX `service_api_key_key_id_key`(`key_id`),
    UNIQUE INDEX `service_api_key_token_hash_key`(`token_hash`),
    INDEX `idx_service_api_key_customer`(`customer_id`, `is_active`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

ALTER TABLE `service_api_key`
    ADD CONSTRAINT `service_api_key_customer_id_fkey`
    FOREIGN KEY (`customer_id`) REFERENCES `host_customer`(`customer_id`)
    ON DELETE RESTRICT ON UPDATE CASCADE;
