-- Migration 083: ZOPK data cleanup and normalization
-- Date: 2026-03-15
-- Description:
--   1. Normalize entity types (Polish → English)
--   2. Clean up stale fetch jobs
--   3. Grant permissions

-- ============================================================
-- 1. Normalize entity types (Polish → English)
-- ============================================================

UPDATE zopk_knowledge_entities SET entity_type = 'organization' WHERE entity_type = 'Organizacja';
UPDATE zopk_knowledge_entities SET entity_type = 'place' WHERE entity_type = 'Lokalizacja';
UPDATE zopk_knowledge_entities SET entity_type = 'person' WHERE entity_type = 'Osoba';
UPDATE zopk_knowledge_entities SET entity_type = 'project' WHERE entity_type = 'Projekt';
UPDATE zopk_knowledge_entities SET entity_type = 'company' WHERE entity_type = 'Dokument/Umowa';
UPDATE zopk_knowledge_entities SET entity_type = 'organization' WHERE entity_type = 'Kraj/Narodowość';
UPDATE zopk_knowledge_entities SET entity_type = 'technology' WHERE entity_type = 'Element techniczny';

-- ============================================================
-- 2. Clean up stale fetch jobs (stuck in 'running' status)
-- ============================================================

UPDATE zopk_news_fetch_jobs
SET status = 'failed',
    error_message = 'Automatycznie zakończony — utknął w statusie running',
    completed_at = NOW()
WHERE status = 'running'
AND started_at < NOW() - INTERVAL '1 hour';
