-- CreateTable
CREATE TABLE `users` (
  `id` INT NOT NULL,
  `username` VARCHAR(191) NOT NULL DEFAULT '',
  `display_name` VARCHAR(191) NOT NULL DEFAULT '',
  `group` VARCHAR(191) NOT NULL DEFAULT '',
  `role` INT NOT NULL DEFAULT 0,
  `status` INT NOT NULL DEFAULT 0,
  `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`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `image_generations` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT NOT NULL,
  `prompt` TEXT NOT NULL,
  `status` ENUM('QUEUED', 'RUNNING', 'SUCCEEDED', 'FAILED') NOT NULL DEFAULT 'RUNNING',
  `model` VARCHAR(64) NOT NULL DEFAULT 'gpt-image-2',
  `size` VARCHAR(32) NOT NULL DEFAULT '1024x1024',
  `started_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `ended_at` DATETIME(3) NULL,
  `duration_ms` INT NULL,
  `image_url` VARCHAR(2048) NULL,
  `image_base64` LONGTEXT NULL,
  `image_mime_type` VARCHAR(191) NULL,
  `revised_prompt` TEXT NULL,
  `upstream_response` JSON NULL,
  `error_message` TEXT 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) NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `generation_stats` (
  `id` VARCHAR(32) NOT NULL,
  `total_requests` INT NOT NULL DEFAULT 0,
  `success_requests` INT NOT NULL DEFAULT 0,
  `failed_requests` INT NOT NULL DEFAULT 0,
  `queued_requests` INT NOT NULL DEFAULT 0,
  `running_requests` INT NOT NULL DEFAULT 0,
  `total_images` INT NOT NULL DEFAULT 0,
  `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`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateIndex
CREATE INDEX `image_generations_user_id_created_at_idx` ON `image_generations`(`user_id`, `created_at`);

-- CreateIndex
CREATE INDEX `image_generations_status_idx` ON `image_generations`(`status`);

-- CreateIndex
CREATE INDEX `image_generations_deleted_at_idx` ON `image_generations`(`deleted_at`);

-- AddForeignKey
ALTER TABLE `image_generations`
  ADD CONSTRAINT `image_generations_user_id_fkey`
  FOREIGN KEY (`user_id`) REFERENCES `users`(`id`)
  ON DELETE CASCADE ON UPDATE CASCADE;
