-- Helpdesk module: seed test BC connections for the live dev tenants.
-- Idempotent: re-running is a no-op.
-- Encrypted secrets (basic_password_enc) are AES-256-GCM blobs produced with
-- APP_CRYPTO_KEY=9792a9ce0def59c034a651f2f6f26f3dcda2f78c1e3513e67be4da06afc24680
-- (set in .env.example). Decryption fails if the key differs.
-- Tenant lookup uses uuid so this only matches the live dev tenants seeded
-- by core init.sql; on environments without those tenants the inserts are
-- no-ops (FROM-clause yields zero rows).

-- ─── Per-tenant override: breadcrumb mediasolutions GmbH ───
INSERT INTO `helpdesk_tenant_settings` (
  `tenant_id`, `override_enabled`, `auth_mode`, `odata_base_url`, `company_name`,
  `basic_user`, `basic_password_enc`, `created_at`, `updated_at`
)
SELECT t.id, 1, 'basic',
  'https://bc.icoreon.de:7048/BusinessCentral-NUP/ODataV4',
  'breadcrumb mediasolutions GmbH', 'ICCONNECT',
  'eyJ2IjoxLCJpdiI6IjJYb2NuZENuTnNSaFo4U3kiLCJ0YWciOiJqbHJpcUVkSElXbDBSU1FreFlhSXR3IiwiY3QiOiJlcVVfTXU3SEU2ZVA3aS0wUDBFbUswY3hIdyJ9',
  NOW(), NOW()
FROM tenants t
WHERE t.uuid = '57349d01-262e-11f1-8ada-dab0b621b876'
  AND NOT EXISTS (
    SELECT 1 FROM helpdesk_tenant_settings hts WHERE hts.tenant_id = t.id
  );

-- ─── Per-tenant override: icoreon GmbH ───
INSERT INTO `helpdesk_tenant_settings` (
  `tenant_id`, `override_enabled`, `auth_mode`, `odata_base_url`, `company_name`,
  `basic_user`, `basic_password_enc`, `created_at`, `updated_at`
)
SELECT t.id, 1, 'basic',
  'https://bc.icoreon.de:7048/BusinessCentral-NUP/ODataV4',
  'icoreon GmbH', 'ICCONNECT',
  'eyJ2IjoxLCJpdiI6InAxdDJZWnlVT3JOenNPeDEiLCJ0YWciOiI2bW93dTJHTUdwdzVQSXBqVmlFcm93IiwiY3QiOiIwVW1sTGVuSEJDX21OTmRORThBN3pvRWdvdyJ9',
  NOW(), NOW()
FROM tenants t
WHERE t.uuid = 'ab99e81c-471a-4db0-aa24-c198a5c58557'
  AND NOT EXISTS (
    SELECT 1 FROM helpdesk_tenant_settings hts WHERE hts.tenant_id = t.id
  );

-- ─── Global fallback (used when override_enabled = 0) ───
INSERT INTO `settings` (`key`, `value`, `description`)
VALUES
  ('helpdesk.bc_auth_mode', 'basic', 'helpdesk.bc_auth_mode'),
  ('helpdesk.bc_basic_user', 'ICCONNECT', 'helpdesk.bc_basic_user'),
  ('helpdesk.bc_basic_password_enc', 'eyJ2IjoxLCJpdiI6IlhReDVxbHo3Q1dJSVFINkYiLCJ0YWciOiJyaFV1MHBlc1pSS1Vwb0YxTENyWVhnIiwiY3QiOiI0N2NNMWtjZVNlT3QzcGpfd0lqaDROWEJmUSJ9', 'helpdesk.bc_basic_password_enc'),
  ('helpdesk.bc_company_name', 'breadcrumb mediasolutions GmbH', 'helpdesk.bc_company_name'),
  ('helpdesk.bc_odata_base_url', 'https://bc.icoreon.de:7048/BusinessCentral-NUP/ODataV4', 'helpdesk.bc_odata_base_url')
ON DUPLICATE KEY UPDATE
  `value` = VALUES(`value`);
