import http from 'k6/http';
import { check } from 'k6';

export const options = {
  vus: 10,
  iterations: 200,
};

const SUPABASE_URL = 'https://xavxfqyjrouftkbujtxd.supabase.co';
const SERVICE_ROLE_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhhdnhmcXlqcm91ZnRrYnVqdHhkIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc3NzIwNTMyNiwiZXhwIjoyMDkyNzgxMzI2fQ.DWTn0xIvi6NA32LiVvjfMaX9778VX7n6zp790Pas7a8';

function randomString(len) {
  const chars = 'abcdefghijklmnopqrstuvwxyz';
  let out = '';
  for (let i = 0; i < len; i++) {
    out += chars[Math.floor(Math.random() * chars.length)];
  }
  return out;
}

export default function () {
  const i = __ITER;

  const firstName = randomString(6);
  const lastName = randomString(8);
  const email = `user_${__VU}_${__ITER}_${Math.random().toString(36).substring(2,8)}@test.com`;
  const password = 'TestPassword123!';

  // -----------------------
  // 1. CREATE AUTH USER
  // -----------------------
  const authRes = http.post(
    `${SUPABASE_URL}/auth/v1/admin/users`,
    JSON.stringify({
      email,
      password,
      email_confirm: true,
    }),
    {
      headers: {
        apikey: SERVICE_ROLE_KEY,
        Authorization: `Bearer ${SERVICE_ROLE_KEY}`,
        'Content-Type': 'application/json',
      },
    }
  );

  const userId = authRes.json('id');

  check(authRes, {
    'auth created': (r) => r.status === 200 || r.status === 201,
  });

  if (!userId) {
    console.log('FAILED AUTH:', authRes.status, authRes.body);
    return;
  }

  // -----------------------
  // 2. INSERT PUBLIC PROFILE
  // -----------------------
  const profileRes = http.post(
    `${SUPABASE_URL}/rest/v1/users`,
    JSON.stringify({
      id: userId,
      first_name: firstName,
      last_name: lastName,
    }),
    {
      headers: {
        apikey: SERVICE_ROLE_KEY,
        Authorization: `Bearer ${SERVICE_ROLE_KEY}`,
        'Content-Type': 'application/json',
        Prefer: 'return=representation',
      },
    }
  );

  check(profileRes, {
    'profile created': (r) => r.status === 201,
  });

  if (profileRes.status !== 201) {
    console.log('FAILED PROFILE:', profileRes.status, profileRes.body);
  }
}