-- Migration 054: Worker Metadata for Named Workforce
-- Adds worker_name and worker_role to job tables for displaying friendly worker identities

-- Add worker metadata columns to job_schedules
ALTER TABLE job_schedules
  ADD COLUMN IF NOT EXISTS worker_name VARCHAR(50),
  ADD COLUMN IF NOT EXISTS worker_role VARCHAR(100);

COMMENT ON COLUMN job_schedules.worker_name IS 'Friendly name for the worker (e.g., Alice, Henry, Bella, Oscar)';
COMMENT ON COLUMN job_schedules.worker_role IS 'Description of worker role (e.g., Store Discovery Worker, GraphQL Product Sync)';

-- Add worker metadata columns to job_run_logs
ALTER TABLE job_run_logs
  ADD COLUMN IF NOT EXISTS worker_name VARCHAR(50),
  ADD COLUMN IF NOT EXISTS run_role VARCHAR(100);

COMMENT ON COLUMN job_run_logs.worker_name IS 'Name of the worker that executed this run (copied from schedule)';
COMMENT ON COLUMN job_run_logs.run_role IS 'Role description for this specific run';

-- Add worker_name to dispensary_crawl_jobs (for tracking which named worker enqueued it)
ALTER TABLE dispensary_crawl_jobs
  ADD COLUMN IF NOT EXISTS enqueued_by_worker VARCHAR(50);

COMMENT ON COLUMN dispensary_crawl_jobs.enqueued_by_worker IS 'Name of the worker that enqueued this job';

-- Update existing schedules with worker names
UPDATE job_schedules SET
  worker_name = 'Bella',
  worker_role = 'GraphQL Product Sync'
WHERE job_name = 'dutchie_az_product_crawl' AND worker_name IS NULL;

UPDATE job_schedules SET
  worker_name = 'Henry',
  worker_role = 'Entry Point Finder'
WHERE job_name = 'dutchie_az_menu_detection' AND worker_name IS NULL;

UPDATE job_schedules SET
  worker_name = 'Alice',
  worker_role = 'Store Discovery'
WHERE job_name = 'dutchie_store_discovery' AND worker_name IS NULL;

UPDATE job_schedules SET
  worker_name = 'Oscar',
  worker_role = 'Analytics Refresh'
WHERE job_name = 'analytics_refresh' AND worker_name IS NULL;

-- Create index for worker name lookups
CREATE INDEX IF NOT EXISTS idx_job_run_logs_worker_name ON job_run_logs(worker_name);
CREATE INDEX IF NOT EXISTS idx_dispensary_crawl_jobs_enqueued_by ON dispensary_crawl_jobs(enqueued_by_worker);
