const http = require('http');

const request = (path, method, body, token) => {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: '127.0.0.1',
      port: 4100,
      path: '/api' + path,
      method: method,
      headers: {
        'Content-Type': 'application/json'
      }
    };
    if (token) {
      options.headers['Authorization'] = 'Bearer ' + token;
    }
    const req = http.request(options, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => resolve({status: res.statusCode, data: JSON.parse(data || '{}')}));
    });
    req.on('error', reject);
    if (body) req.write(JSON.stringify(body));
    req.end();
  });
};

async function testWorkflow() {
  try {
    console.log("1. Creating Application with NEW Fields");
    const appRes = await request('/applications', 'POST', {
      name: "Renewal Tester Notary",
      region: "Banaadir",
      district: "Hodon",
      category: "B",
      applicant_name: "Test User",
      applicant_email: "test.renew@notary.so",
      applicant_phone: "000000",
      license_file: "uploads/renew.pdf",
      registration_type: "renewed",
      issued_date: "2026-01-01",
      expired_date: "2027-01-01"
    });
    console.log(appRes.data);
    const appId = appRes.data.id;

    console.log("\n2. Login as Admin");
    const loginRes = await request('/auth/login', 'POST', {
      email: "admin@enotary.gov",
      password: "admin123"
    });
    const adminToken = loginRes.data.token;

    console.log("\n3. Approve Application");
    const approveRes = await request(`/applications/${appId}/review`, 'PATCH', {
      status: "active"
    }, adminToken);
    console.log("Approval Status:", approveRes.status);
    console.log(approveRes.data.credentials);
    
    console.log("\nWorkflow Test Complete!");

  } catch (err) {
    console.error(err);
  }
}

testWorkflow();
