SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_user;

-- apps 是 App 目录于后台与 gateway 共用的事实源；Logo 只是稳定展示元数据，不参与租户解析或鉴权。
SET @apps_logo_column_exists = (
  SELECT COUNT(*)
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'apps'
    AND COLUMN_NAME = 'logo_url'
);
SET @apps_logo_ddl = IF(
  @apps_logo_column_exists = 0,
  'ALTER TABLE apps ADD COLUMN logo_url VARCHAR(1024) NOT NULL DEFAULT '''' COMMENT ''应用 Logo 的公网访问地址'', ALGORITHM=INSTANT',
  'SELECT 1'
);
PREPARE apps_logo_stmt FROM @apps_logo_ddl;
EXECUTE apps_logo_stmt;
DEALLOCATE PREPARE apps_logo_stmt;

SET @now_ms = CAST(UNIX_TIMESTAMP(UTC_TIMESTAMP(3)) * 1000 AS UNSIGNED);

-- 用 app_code 唯一索引定点更新；Aslan/Yumi 若仅作为 legacy 财务源不在表内，本语句不会为其创建可被 gateway 解析的租户记录。
UPDATE apps
SET logo_url = CASE app_code
    WHEN 'lalu' THEN 'https://media.haiyihy.com/admin/apps/logos/lalu.png'
    WHEN 'huwaa' THEN 'https://media.haiyihy.com/admin/apps/logos/huwaa.png'
    WHEN 'fami' THEN 'https://media.haiyihy.com/admin/apps/logos/fami.png'
    WHEN 'aslan' THEN 'https://media.haiyihy.com/admin/apps/logos/aslan.png'
    WHEN 'yumi' THEN 'https://media.haiyihy.com/admin/apps/logos/yumi.png'
    ELSE logo_url
  END,
  updated_at_ms = @now_ms
WHERE app_code IN ('lalu', 'huwaa', 'fami', 'aslan', 'yumi')
  AND logo_url <> CASE app_code
    WHEN 'lalu' THEN 'https://media.haiyihy.com/admin/apps/logos/lalu.png'
    WHEN 'huwaa' THEN 'https://media.haiyihy.com/admin/apps/logos/huwaa.png'
    WHEN 'fami' THEN 'https://media.haiyihy.com/admin/apps/logos/fami.png'
    WHEN 'aslan' THEN 'https://media.haiyihy.com/admin/apps/logos/aslan.png'
    WHEN 'yumi' THEN 'https://media.haiyihy.com/admin/apps/logos/yumi.png'
    ELSE logo_url
  END;
