-- Rename the Swedish schema to neutral English
--
-- Generated by scripts/generate_rename_migration.py from _postgres/rename_map.py.
-- Do not edit by hand; edit the map and regenerate.
--
-- ALTER TABLE ... RENAME is catalog-only in PostgreSQL: no table rewrite, no data
-- movement, no index rebuild. Wall time is milliseconds regardless of row count,
-- and the HNSW vector indexes are not touched.
--
-- Guarded by an existence check, so this is a no-op on a database created from the
-- current schema.sql and does the work on one created before the rename. One file
-- serves both a fresh install and an existing deployment.

BEGIN;

SET LOCAL lock_timeout = '5s';
SET LOCAL statement_timeout = 0;

DO $rename$
BEGIN
IF EXISTS (SELECT 1 FROM information_schema.columns
        WHERE table_schema = 'public' AND table_name = 'talks'
          AND column_name = 'anforandetext') THEN
    -- columns (still on their original tables)
    ALTER TABLE people RENAME COLUMN intressent_id TO person_id;
    ALTER TABLE people RENAME COLUMN hangar_id TO source_record_id;
    ALTER TABLE people RENAME COLUMN hangar_guid TO source_record_guid;
    ALTER TABLE people RENAME COLUMN sourceid TO source_id;
    ALTER TABLE people RENAME COLUMN fodd_ar TO birth_year;
    ALTER TABLE people RENAME COLUMN kon TO gender;
    ALTER TABLE people RENAME COLUMN efternamn TO last_name;
    ALTER TABLE people RENAME COLUMN tilltalsnamn TO first_name;
    ALTER TABLE people RENAME COLUMN sorteringsnamn TO sort_name;
    ALTER TABLE people RENAME COLUMN iort TO home_town;
    ALTER TABLE people RENAME COLUMN parti TO party;
    ALTER TABLE people RENAME COLUMN valkrets TO constituency;
    ALTER TABLE people RENAME COLUMN person_url_xml TO source_url;
    ALTER TABLE people RENAME COLUMN bild_url_80 TO image_url_small;
    ALTER TABLE people RENAME COLUMN bild_url_192 TO image_url_medium;
    ALTER TABLE people RENAME COLUMN bild_url_max TO image_url_large;
    ALTER TABLE people RENAME COLUMN personuppdrag TO assignments;
    ALTER TABLE people RENAME COLUMN personuppgift TO contact_details;
    ALTER TABLE people RENAME COLUMN namn TO name;
    ALTER TABLE people RENAME COLUMN aktiv TO active;
    ALTER TABLE talks RENAME COLUMN anforande_id TO source_speech_id;
    ALTER TABLE talks RENAME COLUMN anforandetext TO text;
    ALTER TABLE talks RENAME COLUMN avsnittsrubrik TO section_title;
    ALTER TABLE talks RENAME COLUMN anforande_nummer TO sequence;
    ALTER TABLE talks RENAME COLUMN kammaraktivitet TO activity_type;
    ALTER TABLE talks RENAME COLUMN talare TO speaker_name;
    ALTER TABLE talks RENAME COLUMN parti TO party;
    ALTER TABLE talks RENAME COLUMN intressent_id TO person_id;
    ALTER TABLE talks RENAME COLUMN datum TO date;
    ALTER TABLE talks RENAME COLUMN dok_datum TO source_datetime;
    ALTER TABLE talks RENAME COLUMN period TO session_year;
    ALTER TABLE talks RENAME COLUMN rel_dok_id TO related_doc_id;
    ALTER TABLE talks RENAME COLUMN dok_nummer TO source_doc_number;
    ALTER TABLE talks RENAME COLUMN hangar_id TO source_record_id;
    ALTER TABLE talks RENAME COLUMN dok_id TO source_doc_id;
    ALTER TABLE talks RENAME COLUMN titel TO title;
    ALTER TABLE talks RENAME COLUMN debate TO debate_id;
    ALTER TABLE talks RENAME COLUMN replik TO is_reply;
    ALTER TABLE talks RENAME COLUMN debateurl TO url_video;
    ALTER TABLE talks RENAME COLUMN audiofileurl TO url_audio_file;
    ALTER TABLE talks RENAME COLUMN startpos TO audio_start_seconds;
    ALTER TABLE chunks RENAME COLUMN talk_id TO speech_id;
    ALTER TABLE debates RENAME COLUMN debate TO id;
    ALTER TABLE debates RENAME COLUMN datum TO date;
    ALTER TABLE motions RENAME COLUMN dok_id TO doc_id;
    ALTER TABLE motions RENAME COLUMN hangar_id TO source_record_id;
    ALTER TABLE motions RENAME COLUMN rm TO session_label;
    ALTER TABLE motions RENAME COLUMN beteckning TO designation;
    ALTER TABLE motions RENAME COLUMN subtyp TO subtype;
    ALTER TABLE motions RENAME COLUMN organ TO committee;
    ALTER TABLE motions RENAME COLUMN datum TO date;
    ALTER TABLE motions RENAME COLUMN systemdatum TO source_updated_at;
    ALTER TABLE motions RENAME COLUMN publicerad TO published_at;
    ALTER TABLE motions RENAME COLUMN year TO session_year;
    ALTER TABLE motions RENAME COLUMN titel TO title;
    ALTER TABLE motions RENAME COLUMN undertitel TO subtitle;
    ALTER TABLE motions RENAME COLUMN forslag_text TO proposals_text;
    ALTER TABLE motions RENAME COLUMN dokument_url_text TO url_text;
    ALTER TABLE motions RENAME COLUMN dokument_url_html TO url_html;
    ALTER TABLE motions RENAME COLUMN pdf_url TO url_pdf;
    ALTER TABLE motions RENAME COLUMN forslag TO proposals_raw;
    ALTER TABLE motions RENAME COLUMN bilagor TO attachments;
    ALTER TABLE motions RENAME COLUMN num_yrkanden TO num_proposals;
    ALTER TABLE motion_authors RENAME COLUMN dok_id TO doc_id;
    ALTER TABLE motion_authors RENAME COLUMN intressent_id TO person_id;
    ALTER TABLE motion_authors RENAME COLUMN namn TO name;
    ALTER TABLE motion_authors RENAME COLUMN partibet TO party;
    ALTER TABLE motion_authors RENAME COLUMN roll TO role;
    ALTER TABLE motion_chunks RENAME COLUMN motion_id TO doc_id;
    ALTER TABLE motion_yrkanden RENAME COLUMN dok_id TO doc_id;
    ALTER TABLE motion_yrkanden RENAME COLUMN nummer TO number;
    ALTER TABLE motion_yrkanden RENAME COLUMN lydelse TO text;
    ALTER TABLE motion_yrkanden RENAME COLUMN utskottet TO committee_recommendation;
    ALTER TABLE motion_yrkanden RENAME COLUMN kammaren TO chamber_decision;
    ALTER TABLE motion_yrkanden RENAME COLUMN behandlas_i TO handled_in;
    ALTER TABLE chat_sessions RENAME COLUMN intressent_id TO person_id;
    ALTER TABLE chat_sessions RENAME COLUMN initial_talk_id TO initial_speech_id;
    ALTER TABLE chat_snapshots RENAME COLUMN intressent_id TO person_id;
    ALTER TABLE chat_snapshots RENAME COLUMN initial_talk_id TO initial_speech_id;

    -- tables
    ALTER TABLE talks RENAME TO speeches;
    ALTER TABLE chunks RENAME TO speech_chunks;
    ALTER TABLE motions RENAME TO documents;
    ALTER TABLE motion_chunks RENAME TO document_chunks;
    ALTER TABLE motion_authors RENAME TO document_authors;
    ALTER TABLE motion_yrkanden RENAME TO document_proposals;

    -- New: lets bills, written questions and committee reports share this
    -- table instead of needing one table per document type. ADD COLUMN with a
    -- constant default is metadata-only in PostgreSQL 11+.
    ALTER TABLE documents ADD COLUMN IF NOT EXISTS doc_type TEXT NOT NULL DEFAULT 'motion';

    -- indexes (cosmetic, but keeps pg_dump diffs readable)
    ALTER INDEX IF EXISTS talks_search_idx RENAME TO speeches_search_idx;
    ALTER INDEX IF EXISTS talks_debate_idx RENAME TO speeches_debate_idx;
    ALTER INDEX IF EXISTS talks_parti_idx RENAME TO speeches_party_idx;
    ALTER INDEX IF EXISTS talks_datum_idx RENAME TO speeches_date_idx;
    ALTER INDEX IF EXISTS talks_year_idx RENAME TO speeches_year_idx;
    ALTER INDEX IF EXISTS talks_intressent_idx RENAME TO speeches_person_idx;
    ALTER INDEX IF EXISTS talks_talare_idx RENAME TO speeches_speaker_idx;
    ALTER INDEX IF EXISTS talks_dok_id_idx RENAME TO speeches_source_doc_idx;
    ALTER INDEX IF EXISTS talks_summary_embedding_idx RENAME TO speeches_summary_embedding_idx;
    ALTER INDEX IF EXISTS chunks_talk_idx RENAME TO speech_chunks_speech_idx;
    ALTER INDEX IF EXISTS chunks_embedding_idx RENAME TO speech_chunks_embedding_idx;
    ALTER INDEX IF EXISTS debates_datum_idx RENAME TO debates_date_idx;
    ALTER INDEX IF EXISTS motions_search_idx RENAME TO documents_search_idx;
    ALTER INDEX IF EXISTS motions_datum_idx RENAME TO documents_date_idx;
    ALTER INDEX IF EXISTS motions_year_idx RENAME TO documents_session_year_idx;
    ALTER INDEX IF EXISTS motions_organ_idx RENAME TO documents_committee_idx;
    ALTER INDEX IF EXISTS motions_parties_idx RENAME TO documents_parties_idx;
    ALTER INDEX IF EXISTS motion_authors_intressent_idx RENAME TO document_authors_person_idx;
    ALTER INDEX IF EXISTS motion_chunks_motion_idx RENAME TO document_chunks_doc_idx;
    ALTER INDEX IF EXISTS motion_chunks_embedding_idx RENAME TO document_chunks_embedding_idx;
    ALTER INDEX IF EXISTS motion_yrkanden_dok_idx RENAME TO document_proposals_doc_idx;
    ALTER INDEX IF EXISTS motion_yrkanden_embedding_idx RENAME TO document_proposals_embedding_idx;
END IF;
END
$rename$;

-- Recreate the search-vector triggers against the new column names.
--
-- The text-search configuration is read from a database setting rather than
-- hardcoded, so a deployment in another language does not have to patch DDL:
--     ALTER DATABASE <db> SET app.fts_config = 'swedish';
-- It only takes effect for new sessions, so restart the API afterwards.

DROP TRIGGER IF EXISTS talks_search_vector_trigger ON speeches;
DROP TRIGGER IF EXISTS speeches_search_vector_trigger ON speeches;
DROP FUNCTION IF EXISTS talks_search_vector_update();

CREATE OR REPLACE FUNCTION speeches_search_vector_update() RETURNS TRIGGER AS $fn$
BEGIN
    NEW.search_vector := to_tsvector(
        COALESCE(current_setting('app.fts_config', true), 'simple')::regconfig,
        coalesce(NEW.text, ''));
    RETURN NEW;
END;
$fn$ LANGUAGE plpgsql;

CREATE TRIGGER speeches_search_vector_trigger
    BEFORE INSERT OR UPDATE OF text ON speeches
    FOR EACH ROW EXECUTE FUNCTION speeches_search_vector_update();

DROP TRIGGER IF EXISTS motions_search_vector_trigger ON documents;
DROP TRIGGER IF EXISTS documents_search_vector_trigger ON documents;
DROP FUNCTION IF EXISTS motions_search_vector_update();

CREATE OR REPLACE FUNCTION documents_search_vector_update() RETURNS TRIGGER AS $fn$
DECLARE cfg regconfig := COALESCE(current_setting('app.fts_config', true), 'simple')::regconfig;
BEGIN
    NEW.search_vector :=
        setweight(to_tsvector(cfg, coalesce(NEW.title, '')), 'A') ||
        setweight(to_tsvector(cfg, coalesce(NEW.proposals_text, '')), 'B') ||
        setweight(to_tsvector(cfg, coalesce(NEW.subtitle, '')), 'C') ||
        setweight(to_tsvector(cfg, coalesce(NEW.text, '')), 'D');
    RETURN NEW;
END;
$fn$ LANGUAGE plpgsql;

CREATE TRIGGER documents_search_vector_trigger
    BEFORE INSERT OR UPDATE OF title, subtitle, text, proposals_text ON documents
    FOR EACH ROW EXECUTE FUNCTION documents_search_vector_update();

COMMIT;
