-- Add RBAC columns to existing reports table (requires ALTER — run as MySQL/MariaDB root).
-- App user androidcast typically has SELECT,INSERT,UPDATE,DELETE only.
--
--   mysql -u root -p androidcast_crashes < sql/migrations/002_reports_company_columns.sql
--
-- If 001_rbac_companies.sql was not applied yet, run that first.

USE androidcast_crashes;

INSERT IGNORE INTO companies (id, slug, name) VALUES (1, 'default', 'Default');

ALTER TABLE reports
  ADD COLUMN IF NOT EXISTS company_id INT UNSIGNED NOT NULL DEFAULT 1 AFTER id,
  ADD COLUMN IF NOT EXISTS device_id BIGINT UNSIGNED NULL AFTER company_id;

UPDATE reports SET company_id = 1 WHERE company_id IS NULL OR company_id = 0;

ALTER TABLE reports ADD INDEX IF NOT EXISTS idx_reports_company (company_id);
ALTER TABLE reports ADD INDEX IF NOT EXISTS idx_reports_device (device_id);

INSERT IGNORE INTO company_memberships (user_id, company_id, role)
SELECT u.id, 1,
  CASE WHEN LOWER(u.role) IN ('root', 'admin', 'platform_admin') THEN 'owner' ELSE 'member' END
FROM users u;
