-- Arrange-data for the contract lifecycle specs, applied after seed-users.sql.
-- Idempotent. Two things the app cannot provide without manual steps:
--
-- 1. chief gets `edr_freight_app:admin` (customer-profile approval is
--    FreightAdmin-guarded and no seeded position carries it).
-- 2. user@gmail.com gets an ACTIVE company + approved importer profile so the
--    contract wizard is reachable without first running the onboarding journey.

-- 1. chief → edr_freight_app:admin
INSERT INTO iam.position_permissions (id, position_id, permission_id)
SELECT gen_random_uuid(), p.id, perm.id
FROM iam.positions p
JOIN iam.permissions perm ON perm.key = 'edr_freight_app:admin'
WHERE p.key = 'chief'
  AND NOT EXISTS (
    SELECT 1 FROM iam.position_permissions pp
    WHERE pp.position_id = p.id AND pp.permission_id = perm.id
  );

-- 2a. Active customer company (TIN is the idempotency key).
INSERT INTO freight.companies
  (id, name, type, status, tin, fan_number, country, address, phone, email,
   nationality, kind, attributes)
SELECT gen_random_uuid(), 'E2E Logistics PLC', 'customer', 'active',
  '0102030405', '1234567890123456', 'Ethiopia', 'Addis Ababa, Ethiopia',
  '+251911000001', 'ops@e2e-logistics.test', 'ethiopian', 'commercial',
  '{"contactPersonName":"Test Contact","contactPersonPhone":"+251911000002","generalManagerName":"Test GM","generalManagerEmail":"gm@e2e-logistics.test","generalManagerPhone":"+251911000003"}'::jsonb
WHERE NOT EXISTS (SELECT 1 FROM freight.companies WHERE tin = '0102030405');

-- 2b. Approved importer profile (reference normally minted on approval).
INSERT INTO freight.company_profiles (id, company_id, type, status, reference)
SELECT gen_random_uuid(), c.id, 'importer', 'active', 'IMP-E2E-0001'
FROM freight.companies c
WHERE c.tin = '0102030405'
  AND NOT EXISTS (
    SELECT 1 FROM freight.company_profiles p
    WHERE p.company_id = c.id AND p.type = 'importer'
  );

-- 2c. Link the demo portal user to the company, onboarding already done.
-- (active_profile_type was dropped by migration 2450 — the "active mode"
-- column no longer exists; bookings resolve the profile per shipment.)
INSERT INTO freight.external_profiles
  (id, user_id, company_id, first_name, last_name, is_primary_contact,
   onboarding_step, onboarding_completed)
SELECT gen_random_uuid(), u.id, c.id, 'Demo', 'User', true,
  'done', true
FROM iam.users u
JOIN freight.companies c ON c.tin = '0102030405'
WHERE u.email = 'user@gmail.com'
  AND NOT EXISTS (
    SELECT 1 FROM freight.external_profiles ep WHERE ep.user_id = u.id
  );
