const { execSync } = require('child_process');
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();
  });
};

const executeSql = (query) => {
  execSync(`"C:\\xampp\\mysql\\bin\\mysql.exe" -u root -D e_notary -e "${query}"`);
};

async function testExpiration() {
  try {
    const loginRes = await request('/auth/login', 'POST', {
      email: "owner@notary.so",
      password: "owner123"
    });
    const ownerToken = loginRes.data.token;
    const notaryId = loginRes.data.user.notary.id;
    console.log("Notary ID:", notaryId, "Token:", ownerToken);

    console.log("\n1. Test Normal Operation");
    let res = await request('/staff', 'GET', null, ownerToken);
    console.log("GET /staff Status:", res.status);

    console.log("\n2. Simulate 1-day expired (Grace Period)");
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    executeSql(`UPDATE notaries SET expired_date = '${yesterday.toISOString().split('T')[0]}' WHERE id = ${notaryId}`);
    
    res = await request('/transactions', 'GET', null, ownerToken);
    console.log("GET /transactions Status (Should be 200, view only):", res.status);
    
    res = await request('/staff', 'POST', { name: "Test", email: "q@q.com", role: "teller" }, ownerToken);
    console.log("POST /staff Status (Should be 403, read-only):", res.status, res.data.message);

    console.log("\n3. Simulate 5-days expired (Locked Out)");
    const fiveDaysAgo = new Date();
    fiveDaysAgo.setDate(fiveDaysAgo.getDate() - 5);
    executeSql(`UPDATE notaries SET expired_date = '${fiveDaysAgo.toISOString().split('T')[0]}' WHERE id = ${notaryId}`);

    res = await request('/transactions', 'GET', null, ownerToken);
    console.log("GET /transactions Status (Should be 403, fully locked out):", res.status, res.data.message);

    console.log("\n4. Ministry of Justice Renews the Notary");
    const adminLogin = await request('/auth/login', 'POST', {
      email: "justice@enotary.gov",
      password: "justice123"
    });
    const adminToken = adminLogin.data.token;

    const nextYear = new Date();
    nextYear.setFullYear(nextYear.getFullYear() + 1);
    res = await request(`/notaries/${notaryId}/renew`, 'PATCH', {
      issued_date: new Date().toISOString().split('T')[0],
      expired_date: nextYear.toISOString().split('T')[0]
    }, adminToken);
    console.log("Renew Action Status:", res.status, res.data.message);

    console.log("\n5. Test Normal Operation Restored");
    res = await request('/transactions', 'GET', null, ownerToken);
    console.log("GET /transactions Status (Should be 200):", res.status);

    process.exit(0);
  } catch (err) {
    console.error(err);
    process.exit(1);
  }
}

testExpiration();
