-- Align legacy TED procurement_document table with the current JPA entity.

ALTER TABLE TED.procurement_document
    ADD COLUMN IF NOT EXISTS notice_url VARCHAR(255);

ALTER TABLE TED.procurement_document
    ADD COLUMN IF NOT EXISTS issue_datetime TIMESTAMP WITH TIME ZONE;

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'ted'
          AND table_name = 'procurement_document'
          AND column_name = 'issue_date'
    ) THEN
        UPDATE TED.procurement_document
        SET issue_datetime = (issue_date + COALESCE(issue_time, TIME '00:00')) AT TIME ZONE current_setting('TIMEZONE')
        WHERE issue_datetime IS NULL
          AND issue_date IS NOT NULL;
    END IF;
END
$$;

ALTER TABLE TED.procurement_document
    ADD COLUMN IF NOT EXISTS embedding_token_count INTEGER;

ALTER TABLE TED.procurement_document
    ALTER COLUMN buyer_city TYPE TEXT;

ALTER TABLE TED.procurement_document
    ALTER COLUMN buyer_postal_code TYPE TEXT;

ALTER TABLE TED.procurement_document
    ALTER COLUMN internal_reference TYPE TEXT;

ALTER TABLE TED.procurement_lot
    ALTER COLUMN internal_id TYPE TEXT;
