-- Migration 058: Add ID resolution tracking columns to dispensaries
--
-- Supports Henry (Entry Point Finder) worker tracking:
-- - id_resolution_attempts: Count of how many times we've tried to resolve platform ID
-- - last_id_resolution_at: When we last tried (matches code expectation)
-- - id_resolution_status: Current status (pending, resolved, failed)
-- - id_resolution_error: Last error message from resolution attempt

-- ============================================================
-- 1. ADD ID RESOLUTION COLUMNS TO dispensaries
-- ============================================================

ALTER TABLE dispensaries
  ADD COLUMN IF NOT EXISTS id_resolution_attempts INTEGER DEFAULT 0,
  ADD COLUMN IF NOT EXISTS last_id_resolution_at TIMESTAMPTZ,
  ADD COLUMN IF NOT EXISTS id_resolution_status VARCHAR(20) DEFAULT 'pending',
  ADD COLUMN IF NOT EXISTS id_resolution_error TEXT;

COMMENT ON COLUMN dispensaries.id_resolution_attempts IS 'Number of attempts to resolve platform_dispensary_id';
COMMENT ON COLUMN dispensaries.last_id_resolution_at IS 'Timestamp of last ID resolution attempt';
COMMENT ON COLUMN dispensaries.id_resolution_status IS 'Status: pending, resolved, failed';
COMMENT ON COLUMN dispensaries.id_resolution_error IS 'Last error message from ID resolution attempt';

-- Additional columns needed by worker/scheduler
ALTER TABLE dispensaries
  ADD COLUMN IF NOT EXISTS failed_at TIMESTAMPTZ,
  ADD COLUMN IF NOT EXISTS failure_notes TEXT;

COMMENT ON COLUMN dispensaries.failed_at IS 'Timestamp when dispensary was marked as permanently failed';
COMMENT ON COLUMN dispensaries.failure_notes IS 'Notes about why dispensary was marked as failed';

-- ============================================================
-- 2. CREATE INDEX FOR RESOLUTION QUERIES
-- ============================================================

CREATE INDEX IF NOT EXISTS idx_dispensaries_id_resolution_status
  ON dispensaries(id_resolution_status)
  WHERE id_resolution_status = 'pending';

-- ============================================================
-- 3. RECORD MIGRATION
-- ============================================================

INSERT INTO schema_migrations (version, name, applied_at)
VALUES (58, '058_add_id_resolution_columns', NOW())
ON CONFLICT (version) DO NOTHING;
