-- Shared DB SAFE tenant foundation pass
-- Purpose: additive only. No drops. No renames. No risky NOT NULL changes.

-- users is already expected to have company_id, staff_code, full_name.
-- The statements below are safe if those columns are missing in some environments.
ALTER TABLE users
  ADD COLUMN IF NOT EXISTS company_id BIGINT(20) UNSIGNED NULL AFTER id,
  ADD COLUMN IF NOT EXISTS staff_code VARCHAR(50) NULL AFTER company_id,
  ADD COLUMN IF NOT EXISTS full_name VARCHAR(150) NULL AFTER staff_code;

-- work_sessions
ALTER TABLE work_sessions
  ADD COLUMN IF NOT EXISTS company_id BIGINT(20) UNSIGNED NULL AFTER user_id;

-- work_session_events
ALTER TABLE work_session_events
  ADD COLUMN IF NOT EXISTS company_id BIGINT(20) UNSIGNED NULL AFTER work_session_id,
  ADD COLUMN IF NOT EXISTS user_id BIGINT(20) UNSIGNED NULL AFTER company_id;

-- Optional shared-DB compatibility additions.
-- These are safe because they only add nullable columns if missing.
ALTER TABLE api_sessions
  ADD COLUMN IF NOT EXISTS company_id BIGINT(20) UNSIGNED NULL AFTER user_id;

ALTER TABLE worksites
  ADD COLUMN IF NOT EXISTS company_id BIGINT(20) UNSIGNED NULL AFTER id;

ALTER TABLE user_worksites
  ADD COLUMN IF NOT EXISTS company_id BIGINT(20) UNSIGNED NULL AFTER user_id;

ALTER TABLE location_logs
  ADD COLUMN IF NOT EXISTS company_id BIGINT(20) UNSIGNED NULL AFTER user_id;

ALTER TABLE location_stops
  ADD COLUMN IF NOT EXISTS company_id BIGINT(20) UNSIGNED NULL AFTER user_id;

ALTER TABLE admin_audit_log
  ADD COLUMN IF NOT EXISTS company_id BIGINT(20) UNSIGNED NULL AFTER admin_user_id;
