scenarios:
  - id: naming-refactor
    title: "Fix Bad Variable and Function Names"
    difficulty: beginner
    xp: 25
    setup:
      - "mkdir -p workshop && cd workshop"
    files:
      - name: utils.js
        content: |
          function d(x) {
            return x * 2;
          }
          function t(a, b) {
            return a + b;
          }
          let a = [1, 2, 3];
          let r = a.map(i => i * 3);
          let m = r.reduce((p, c) => p + c, 0);
          module.exports = { d, t };
        language: javascript
        readonly: false
    task: "Rename all variables and functions to be meaningful and self-documenting. A reader should understand what the code does from names alone."
    validations:
      - label: "utils.js was refactored with clear names"
        check: file-changed
        pattern: "utils.js"
    hints:
      - "What does 'd' do? What would you call a function that doubles a number?"
      - "Consider: inputValue, doubledValue, numbers, tripledNumbers, sum."
      - "Names like double, add, numbers, tripledNumbers, total improve readability."
    agent_prompts:
      on_start: "When you look at this code, what story do the names tell? What would a new teammate guess each function does?"

  - id: extract-functions
    title: "Extract a Long Function into Smaller Ones"
    difficulty: intermediate
    xp: 30
    setup:
      - "mkdir -p workshop && cd workshop"
    files:
      - name: processOrder.js
        content: |
          function processOrder(order) {
            if (!order || typeof order !== 'object') {
              throw new Error('Invalid order');
            }
            if (!order.items || !Array.isArray(order.items) || order.items.length === 0) {
              throw new Error('Order must have at least one item');
            }
            if (!order.customerId || typeof order.customerId !== 'string') {
              throw new Error('Valid customerId required');
            }
            let subtotal = 0;
            for (const item of order.items) {
              if (!item.price || !item.quantity || item.quantity < 1) {
                throw new Error('Each item must have price and quantity >= 1');
              }
              subtotal += item.price * item.quantity;
            }
            const taxRate = 0.08;
            const tax = subtotal * taxRate;
            const total = subtotal + tax;
            const summary = `Order for customer ${order.customerId}: ${order.items.length} items, subtotal $${subtotal.toFixed(2)}, tax $${tax.toFixed(2)}, total $${total.toFixed(2)}`;
            return { subtotal, tax, total, summary };
          }
          module.exports = { processOrder };
        language: javascript
        readonly: false
    task: "Break this 40-line function into 4-5 smaller, focused functions. Each function should do one thing. The main processOrder should orchestrate them."
    validations:
      - label: "processOrder.js was refactored into smaller functions"
        check: file-changed
        pattern: "processOrder.js"
    hints:
      - "Can you identify distinct responsibilities? Validation, calculation, formatting are often separate."
      - "Functions like validateOrder, calculateSubtotal, calculateTax, formatSummary could each handle one concern."
      - "The main function becomes a sequence of calls—easier to read and test."
    agent_prompts:
      on_start: "What different jobs does this function perform? How might splitting them make the code easier to reason about and test?"

  - id: remove-duplication
    title: "Apply DRY—Remove Duplication in Handlers"
    difficulty: intermediate
    xp: 35
    setup:
      - "mkdir -p workshop && cd workshop"
    files:
      - name: handlers.js
        content: |
          function handleCreate(req, res) {
            const body = JSON.parse(req.body || '{}');
            if (!body.name || typeof body.name !== 'string') {
              res.status(400).json({ error: 'Name is required' });
              return;
            }
            const trimmed = body.name.trim();
            if (trimmed.length === 0) {
              res.status(400).json({ error: 'Name cannot be empty' });
              return;
            }
            const item = { id: Date.now(), name: trimmed };
            res.status(201).json(item);
          }

          function handleUpdate(req, res) {
            const body = JSON.parse(req.body || '{}');
            if (!body.name || typeof body.name !== 'string') {
              res.status(400).json({ error: 'Name is required' });
              return;
            }
            const trimmed = body.name.trim();
            if (trimmed.length === 0) {
              res.status(400).json({ error: 'Name cannot be empty' });
              return;
            }
            const item = { id: req.params.id, name: trimmed };
            res.status(200).json(item);
          }

          function handlePatch(req, res) {
            const body = JSON.parse(req.body || '{}');
            if (!body.name || typeof body.name !== 'string') {
              res.status(400).json({ error: 'Name is required' });
              return;
            }
            const trimmed = body.name.trim();
            if (trimmed.length === 0) {
              res.status(400).json({ error: 'Name cannot be empty' });
              return;
            }
            const item = { id: req.params.id, name: trimmed };
            res.status(200).json(item);
          }

          module.exports = { handleCreate, handleUpdate, handlePatch };
        language: javascript
        readonly: false
    task: "Extract the shared validation and logic. The three handlers have nearly identical validation and trimming. Create a helper and reduce duplication."
    validations:
      - label: "handlers.js was refactored to remove duplication"
        check: file-changed
        pattern: "handlers.js"
    hints:
      - "What lines appear in all three handlers? Validation and trimming are identical."
      - "A function like parseAndValidateName(body) could return { valid, error, name }."
      - "Each handler would call the helper and branch on valid/invalid—one place to fix validation bugs."
    agent_prompts:
      on_start: "If the product owner changes the rules for a valid name, how many places would you update today? What would make that number smaller?"
