-- Second tenant for the integration suite: user2@gmail.com gets its own ACTIVE
-- company + approved importer profile, mirroring seed-company.sql (which only
-- sets up user@gmail.com). Two real tenants are what make the cross-tenant
-- isolation and the "two companies race for the same train" scenarios honest.
-- Idempotent; TIN is the key.

INSERT INTO freight.companies
  (id, name, type, status, tin, fan_number, country, address, phone, email,
   nationality, kind, attributes)
SELECT gen_random_uuid(), 'IT Freight Partners PLC', 'customer', 'active',
  '0102030406', '1234567890123457', 'Ethiopia', 'Adama, Ethiopia',
  '+251911000011', 'ops@it-partners.test', 'ethiopian', 'commercial',
  '{"contactPersonName":"IT Contact","contactPersonPhone":"+251911000012","generalManagerName":"IT GM","generalManagerEmail":"gm@it-partners.test","generalManagerPhone":"+251911000013"}'::jsonb
WHERE NOT EXISTS (SELECT 1 FROM freight.companies WHERE tin = '0102030406');

INSERT INTO freight.company_profiles (id, company_id, type, status, reference)
SELECT gen_random_uuid(), c.id, 'importer', 'active', 'IMP-IT-0002'
FROM freight.companies c
WHERE c.tin = '0102030406'
  AND NOT EXISTS (
    SELECT 1 FROM freight.company_profiles p
    WHERE p.company_id = c.id AND p.type = 'importer'
  );

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', 'User2', true, 'done', true
FROM iam.users u
JOIN freight.companies c ON c.tin = '0102030406'
WHERE u.email = 'user2@gmail.com'
  AND NOT EXISTS (
    SELECT 1 FROM freight.external_profiles ep WHERE ep.user_id = u.id
  );
