CREATE TABLE polochons (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    name text NOT NULL,
    url text NOT NULL,
    token text NOT NULL,
    auth_token text NOT NULL DEFAULT gen_random_uuid(),
    admin_id uuid NOT NULL REFERENCES users (id),
    LIKE base INCLUDING DEFAULTS
);

CREATE UNIQUE INDEX ON polochons (id);
CREATE INDEX ON polochons (name);
CREATE TRIGGER update_polochons_updated_at BEFORE UPDATE ON polochons FOR EACH ROW EXECUTE PROCEDURE  update_updated_at_column();

ALTER TABLE users ADD COLUMN polochon_id uuid DEFAULT NULL REFERENCES polochons (id);
ALTER TABLE users ADD COLUMN token text NOT NULL DEFAULT '';
ALTER TABLE users ADD COLUMN polochon_activated boolean NOT NULL DEFAULT false;

CREATE INDEX ON users (polochon_id);

CREATE OR REPLACE FUNCTION migrate_polochons() RETURNS void AS $$
DECLARE
    u RECORD;
    polochon RECORD;
    admin RECORD;
BEGIN
    -- Retrieve the admin
    SELECT * INTO admin FROM users WHERE name = 'admin';

    FOR u IN select * from users LOOP
        -- Check if polochon is configured and the user is activated
        IF u.activated = false OR u.rawconfig->'polochon' IS NULL THEN
                RAISE NOTICE ' => skipping user %', quote_ident(u.name);
                CONTINUE;
        END IF;

        RAISE NOTICE 'SELECT * INTO polochon FROM polochons WHERRE name = %', u.rawconfig->'polochon'->>'url';
        -- Try to get the user's polochon
        SELECT * INTO polochon FROM polochons WHERE name = u.rawconfig->'polochon'->>'url';
        -- If polochon is null, create it
        IF polochon IS NULL THEN
                RAISE NOTICE ' => user % have polochon % not yet created, create it!', quote_ident(u.name), u.rawconfig->'polochon'->>'url';
                INSERT INTO polochons (name, url, token, admin_id)
                VALUES (u.rawconfig->'polochon'->>'url', u.rawconfig->'polochon'->>'url', u.rawconfig->'polochon'->>'token', admin.id)
                RETURNING * INTO polochon;
        END IF;

        RAISE NOTICE ' => user % have polochon %', quote_ident(u.name), u.rawconfig->'polochon'->>'url';
        -- Update the user with the token and polochon_id
        UPDATE
            users
        SET
            token = u.rawconfig->'polochon'->>'token',
            polochon_id = polochon.id,
            polochon_activated = true
        WHERE
            id = u.id;
    END LOOP;
    RAISE NOTICE 'ALL DONE';
END;
$$ LANGUAGE plpgsql;

SELECT * FROM migrate_polochons();
DROP FUNCTION migrate_polochons();
