/**
 * F-138 backfill: convert any legacy `orders_order_history` refund entries that
 * were stored as raw JSON `message` strings into the new human-readable format
 * introduced by `apply-pos-return.ts`. We also move the original payload into
 * the new `metadata` column so internal tooling still has the structured data.
 * @param {import('node-pg-migrate').MigrationBuilder} pgm
 */
export const up = (pgm) => {
  pgm.sql(`
    WITH parsed AS (
      SELECT id,
             (message::jsonb) AS payload,
             (
               CASE (message::jsonb->>'status')
                 WHEN 'refund' THEN 'Devolución total'
                 ELSE 'Devolución parcial'
               END
             ) AS action
      FROM orders_order_history
      WHERE event_type = 'RETURNED'
        AND message ~ '^\\s*\\{'
    ),
    formatted AS (
      SELECT id,
             action || ' de ' ||
               (round(((payload->>'refundedCents')::numeric) / 100)::numeric(12,2)::text) ||
               ' €' ||
               COALESCE(
                 (SELECT ' — ' || string_agg(
                            ((l->>'returnedQuantity')::int)::text || ' × ' ||
                             COALESCE(oi.name, 'Artículo'),
                            ', '
                          ORDER BY ord)
                    FROM jsonb_array_elements(payload->'lines') WITH ORDINALITY AS x(l, ord)
                    LEFT JOIN orders_items oi ON oi.id = (l->>'orderItemId')::uuid
                    WHERE (l->>'returnedQuantity')::int > 0
                 ),
                 ''
               ) ||
               CASE
                 WHEN NULLIF(payload->>'reason', '') IS NOT NULL
                   THEN ' (motivo: ' || (payload->>'reason') || ')'
                 ELSE ''
               END AS readable
      FROM parsed
    )
    UPDATE orders_order_history h
       SET message = f.readable,
           metadata = h.message::jsonb
      FROM formatted f
     WHERE h.id = f.id
  `);
};

export const down = (pgm) => {
  // Best-effort: restore the JSON message from metadata. We can't know whether
  // a row was originally a JSON message or already human-readable, so the
  // down migration just clears the column.
  pgm.sql(`
    UPDATE orders_order_history
       SET message = metadata::text,
           metadata = NULL
     WHERE event_type = 'RETURNED' AND metadata IS NOT NULL
  `);
};
