import dotenv from 'dotenv';
import axios from 'axios';

// Load environment variables
dotenv.config();

const WREN_API_TOKEN = process.env.WREN_API_TOKEN;

if (!WREN_API_TOKEN) {
  console.error('Please set your WREN_API_TOKEN in .env file');
  process.exit(1);
}

// Create API client
const api = axios.create({
  baseURL: 'https://api.wren.co/v1',
  headers: {
    'Authorization': `Bearer ${WREN_API_TOKEN}`,
    'Content-Type': 'application/json'
  }
});

async function main() {
  try {
    // 1. Get available projects
    console.log('Fetching available offset projects...');
    const projectsResponse = await api.get('/projects');
    const projects = projectsResponse.data.projects;
    
    console.log(`Found ${projects.length} projects:\n`);
    projects.forEach(project => {
      console.log(`- ${project.name} (${project.location})`);
      console.log(`  Price: $${project.price_per_ton}/ton`);
      console.log(`  Type: ${project.type}\n`);
    });

    // 2. Create an offset order
    console.log('Creating offset order for 1 ton of CO2...');
    const orderResponse = await api.post('/orders', {
      tons: 1,
      currency: 'USD'
    });
    
    const order = orderResponse.data;
    
    console.log('\nOrder created successfully!');
    console.log('------------------------');
    console.log(`Order ID: ${order.id}`);
    console.log(`Amount: $${order.amount_charged/100}`);
    console.log(`Status: ${order.status}`);
    console.log(`Portfolio: ${order.portfolio.name}`);
    
    // List projects in the portfolio
    console.log('\nPortfolio projects:');
    order.portfolio.projects.forEach(project => {
      console.log(`- ${project.name}`);
    });

  } catch (error) {
    if (error.response) {
      console.error('API Error:', error.response.data);
    } else {
      console.error('Error:', error.message);
    }
    process.exit(1);
  }
}

main();