-- Wrapper function for single store/week processing
-- Called by trigger when a task status changes to 'Fixed'
-- Uses the set-based process_store_metrics_set_based function internally

CREATE OR REPLACE FUNCTION update_store_metrics(
    p_customer_id INTEGER,
    p_store_code TEXT,
    p_week_start_date TEXT,
    p_per_row_timeout TEXT DEFAULT '10s',
    p_total_budget INTERVAL DEFAULT '30s'
)
RETURNS JSONB
LANGUAGE plpgsql
AS $$
DECLARE
    v_started       timestamptz := clock_timestamp();
    v_result_json   jsonb;
BEGIN
    -- Check total budget (though for single store this is less critical)
    -- This is kept for consistency with the trigger's expectations
    IF clock_timestamp() - v_started > p_total_budget THEN
        RETURN jsonb_build_object(
            'error', 'total_budget_exceeded',
            'message', format('Total budget of %s exceeded', p_total_budget)
        );
    END IF;

    -- Call the set-based function with single store/week
    -- Format as comma-separated strings (even though only one value)
    SELECT process_store_metrics_set_based(
        p_store_code,           -- p_store_codes_text (single store as comma-separated)
        p_week_start_date,      -- p_week_start_dates_text (single week as comma-separated)
        p_customer_id,          -- p_customer_id
        p_per_row_timeout       -- p_per_store_timeout
    ) INTO v_result_json;

    RETURN v_result_json;
EXCEPTION
    WHEN OTHERS THEN
        RETURN jsonb_build_object(
            'error', 'update_store_metrics_failed',
            'message', SQLERRM,
            'pg_code', SQLSTATE,
            'customer_id', p_customer_id,
            'store_code', p_store_code,
            'week_start_date', p_week_start_date
        );
END;
$$;

