#!/usr/bin/env node
/**
 * Seed test data for Playwright E2E tests.
 * Creates a test user and sample memos if they don't exist.
 */
const http = require('http');

const BACKEND_URL = process.env.BACKEND_URL || 'http://backend:5000';
const TEST_USER = {
  email: 'test@example.com',
  password: 'testpassword123',
  username: 'testuser',
};

function request(url, options = {}) {
  return new Promise((resolve, reject) => {
    const urlObj = new URL(url);
    const opts = {
      hostname: urlObj.hostname,
      port: urlObj.port,
      path: urlObj.pathname + urlObj.search,
      method: options.method || 'GET',
      headers: options.headers || {},
    };
    if (options.body) {
      opts.headers['Content-Type'] = 'application/json';
      options.body = JSON.stringify(options.body);
    }
    const req = http.request(opts, (res) => {
      let data = '';
      res.on('data', (chunk) => data += chunk);
      res.on('end', () => {
        try {
          const json = JSON.parse(data);
          resolve({ status: res.statusCode, data: json, headers: res.headers });
        } catch {
          resolve({ status: res.statusCode, data: data, headers: res.headers });
        }
      });
    });
    req.on('error', reject);
    if (options.body) req.write(options.body);
    req.end();
  });
}

async function signupUser() {
  console.log('Creating test user...');
  try {
    const res = await request(`${BACKEND_URL}/auth/signup`, {
      method: 'POST',
      body: {
        email: TEST_USER.email,
        password: TEST_USER.password,
        username: TEST_USER.username,
      },
    });
    if (res.status === 200 || res.status === 201) {
      console.log('✅ Created test user:', TEST_USER.email);
      return res.data.token || res.data.access_token;
    } else if (res.status === 409) {
      console.log('ℹ️  Test user already exists, signing in...');
      const signinRes = await request(`${BACKEND_URL}/auth/signin`, {
        method: 'POST',
        body: {
          email: TEST_USER.email,
          password: TEST_USER.password,
        },
      });
      if (signinRes.status === 200) {
        console.log('✅ Signed in as test user');
        return signinRes.data.token || signinRes.data.access_token;
      } else {
        console.error('❌ Failed to sign in:', signinRes.status);
      }
    } else {
      console.error('❌ Signup failed:', res.status, res.data);
    }
  } catch (err) {
    console.error('❌ Error signing up:', err.message);
  }
  return null;
}

async function createSampleMemos(token) {
  console.log('Creating sample memos...');
  const headers = { 'Content-Type': 'application/json' };
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  const memos = [
    'This is a test memo for Playwright E2E tests.',
    'Another test memo with some content.',
    'Third memo - testing comment functionality.',
  ];
  for (const content of memos) {
    try {
      const res = await request(`${BACKEND_URL}/api/v1/memos`, {
        method: 'POST',
        headers,
        body: { content, visibility: 'PUBLIC' },
      });
      if (res.status === 200 || res.status === 201) {
        console.log('✅ Created memo:', content.substring(0, 30) + '...');
      } else if (res.status === 409) {
        console.log('ℹ️  Memo already exists:', content.substring(0, 30) + '...');
      } else {
        console.error('❌ Failed to create memo:', res.status);
      }
    } catch (err) {
      console.error('❌ Error creating memo:', err.message);
    }
  }
}

async function waitForBackend(maxAttempts = 30) {
  console.log('Waiting for backend to be ready...');
  for (let i = 0; i < maxAttempts; i++) {
    try {
      const res = await request(`${BACKEND_URL}/docs`);
      if (res.status < 500) {
        console.log('✅ Backend is ready');
        return true;
      }
    } catch (err) {
      // ignore
    }
    await new Promise(r => setTimeout(r, 2000));
  }
  console.error('❌ Backend did not become ready in time');
  return false;
}

async function main() {
  console.log('🌱 Seeding test data for Playwright E2E tests...');
  if (await waitForBackend()) {
    const token = await signupUser();
    if (token) {
      await createSampleMemos(token);
      console.log('✅ Test data seeding complete!');
    } else {
      console.error('❌ Failed to get auth token');
      process.exit(1);
    }
  } else {
    console.error('❌ Backend not ready');
    process.exit(1);
  }
}

main().catch(console.error);
