-- AI assistant (Phase 1): usage-tracking table, monthly budget column, ai.use permission.

CREATE TABLE `ai_usage` (
  `id` INTEGER NOT NULL AUTO_INCREMENT,
  `user_id` INTEGER NULL,
  `kind` VARCHAR(20) NOT NULL,
  `model` VARCHAR(50) NOT NULL,
  `input_tokens` INTEGER NOT NULL DEFAULT 0,
  `output_tokens` INTEGER NOT NULL DEFAULT 0,
  `cost_usd` DECIMAL(10, 6) NOT NULL DEFAULT 0,
  `created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
  PRIMARY KEY (`id`),
  INDEX `idx_ai_usage_created` (`created_at`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

ALTER TABLE `company_settings`
  ADD COLUMN `ai_monthly_budget_usd` DECIMAL(10, 2) NULL DEFAULT 50.00;

-- ai.use permission + grant to admin (INSERT IGNORE → idempotent), mirroring
-- the warehouse-permissions migration.
INSERT IGNORE INTO `permissions` (`name`, `display_name`, `module`, `description`, `created_at`) VALUES
  ('ai.use', 'AI asistent', 'ai', 'Používat AI asistenta (chat a import faktur)', NOW());

INSERT IGNORE INTO `role_permissions` (`role_id`, `permission_id`)
SELECT r.id, p.id
FROM   `roles` r
CROSS  JOIN `permissions` p
WHERE  r.name = 'admin'
  AND  p.name = 'ai.use';
