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");
    const appRes = await request('/applications', 'POST', {
      name: "AutoScript Notary",
      region: "Banaadir",
      district: "Xamar",
      category: "A",
      applicant_name: "Auto Tester",
      applicant_email: "auto@test.so",
      applicant_phone: "12345678",
      license_file: "uploads/test.pdf"
    });
    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(approveRes.data.credentials);
    const credentials = approveRes.data.credentials;

    console.log("\n4. Login as New Notary (First Login)");
    const newLoginRes = await request('/auth/login', 'POST', {
      email: credentials.username,
      password: credentials.temporary_password
    });
    console.log("Login Status:", newLoginRes.status);
    console.log("password_must_change:", newLoginRes.data.user.password_must_change);
    const newToken = newLoginRes.data.token;

    console.log("\n5. Change Password");
    const changePassRes = await request('/auth/change-password', 'POST', {
      new_password: "newpassword123"
    }, newToken);
    console.log(changePassRes.data);

    console.log("\n6. Login as New Notary (Second Login)");
    const finalLoginRes = await request('/auth/login', 'POST', {
      email: credentials.username,
      password: "newpassword123"
    });
    console.log("password_must_change:", finalLoginRes.data.user.password_must_change);

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

testWorkflow();
