-- Create versions table and first version
CREATE TABLE IF NOT EXISTS sprav.permalink_photo_versions (
    version_id bigserial PRIMARY KEY,
    created_at timestamp with time zone NOT NULL DEFAULT NOW(),
    is_active boolean
);
UPDATE sprav.permalink_photo_versions SET is_active=false;
INSERT INTO sprav.permalink_photo_versions (is_active) VALUES (true);

-- Set version to existing records
ALTER TABLE sprav.permalink_photo ADD COLUMN IF NOT EXISTS version_id bigint;
UPDATE sprav.permalink_photo SET version_id=
    (SELECT version_id FROM sprav.permalink_photo_versions WHERE is_active);
CREATE INDEX IF NOT EXISTS permalink_photo_version_id_permalink_id_idx
    ON sprav.permalink_photo USING btree(version_id, permalink_id);

-- Finalize version table
ALTER TABLE sprav.permalink_photo
    ALTER COLUMN version_id SET NOT NULL;
ALTER TABLE sprav.permalink_photo DROP CONSTRAINT IF EXISTS permalink_photo_version_id_fkey;
ALTER TABLE sprav.permalink_photo
    ADD FOREIGN KEY (version_id)
    REFERENCES sprav.permalink_photo_versions (version_id);

-- Create view with active version
CREATE OR REPLACE VIEW sprav.permalink_photo_view AS
    SELECT p.* FROM sprav.permalink_photo p
    JOIN sprav.permalink_photo_versions
    USING (version_id)
    WHERE is_active;
