SET
    created_at = CURRENT_TIMESTAMP;

SET
    extra_data =
SELECT
    jsonb_build_object(
        'src_uid',
        src.uid,
        'lg_uid',
        lg.uid,
        'input_type',
        dtp.input_type,
        'placeholder',
        dtp.placeholder
    ) AS obj
FROM
    public.desambiguator_types dtp
    INNER JOIN public.sources AS src ON src.desambiguator_type_id = dtp.id
    INNER JOIN public.logic_groups AS lg ON lg.source_id = src.id
WHERE
    lg.id = :logic_group_id :: int;

SET
    desambiguator = CASE
        $extra_data :: jsonb ->> 'input_type'
        WHEN 'date' THEN to_hex(
            -- Days since 1970-01-01 in hex
            EXTRACT(
                EPOCH
                FROM
                    NOW()
            ) :: bigint
        )
        ELSE :desambiguator
    END;

SET
    uid = format(
        '%s:%s:%s:%s',
        $extra_data :: jsonb ->> 'src_uid',
        $extra_data :: jsonb ->> 'lg_uid',
        :desambiguator,
        :atom
    );

INSERT INTO
    public.entries(
        uid,
        desambiguator,
        text,
        logic_group_id,
        created_at
    )
VALUES
    (
        $uid,
        :desambiguator,
        :text,
        :logic_group_id :: int,
        :date :: date + :time :: time
    ) RETURNING 'redirect' AS component,
    'form.sql' AS link;
