add_business = """
    INSERT INTO businesses (biz_id, permalink, counter_id)
    VALUES ($1, $2, $3)
    ON CONFLICT (biz_id) DO NOTHING
"""

fetch_business_segments_data = """
    SELECT
        biz_id,
        permalink,
        counter_id,
        coalesce(
            array_agg(jsonb_build_object(
                'segment_name', segments.name,
                'cdp_id', segments.cdp_id,
                'cdp_size', segments.cdp_size
            ) ORDER BY name) FILTER ( WHERE segments.type = 'segment' ),
            ARRAY[]::jsonb[]
        ) AS segments,
        coalesce(
            array_agg(jsonb_build_object(
                'label_name', segments.name,
                'cdp_id', segments.cdp_id,
                'cdp_size', segments.cdp_size
            ) ORDER BY name) FILTER ( WHERE segments.type = 'label' ),
            ARRAY[]::jsonb[]
        ) AS labels
    FROM businesses
    LEFT JOIN segments ON businesses.id = segments.business_id
    WHERE biz_id = $1
    GROUP BY businesses.id
"""

add_business_segment = """
    INSERT INTO segments (business_id, name, cdp_id, cdp_size, type)
    SELECT id, $2, $3, $4, $5
    FROM businesses
        WHERE biz_id = $1
"""

list_biz_ids = """
    SELECT coalesce(array_agg(biz_id ORDER BY biz_id), ARRAY[]::bigint[])
    FROM businesses
"""

create_temp_sizes_table = """
    CREATE TEMP TABLE cdp_sizes (
        cdp_id bigint NOT NULL,
        cdp_size bigint NOT NULL
    )
    ON COMMIT DROP;
"""

update_segments_sizes_from_temp_table = """
    UPDATE segments
    SET cdp_size = cdp_sizes.cdp_size
    FROM cdp_sizes
    WHERE segments.cdp_id = cdp_sizes.cdp_id
"""
