const bcrypt = require("bcryptjs");
require("dotenv").config();

const {
  pool,
  testDatabaseConnection
} = require("../config/db");

const ORGANISATION_CODE = "CAGD-STAFF-2026";
const ACCESS_PASSWORD = "CAGD@Records2026";

const createPortalAccess = async () => {
  try {
    await testDatabaseConnection();

    const passwordHash = await bcrypt.hash(
      ACCESS_PASSWORD,
      12
    );

    const [existingRows] = await pool.query(
      `
        SELECT id
        FROM portal_access_settings
        WHERE organisation_code = ?
        LIMIT 1
      `,
      [ORGANISATION_CODE]
    );

    if (existingRows.length > 0) {
      await pool.query(
        `
          UPDATE portal_access_settings
          SET
            password_hash = ?,
            is_active = TRUE,
            valid_from = NOW(),
            valid_until = '2026-12-31 23:59:59'
          WHERE organisation_code = ?
        `,
        [
          passwordHash,
          ORGANISATION_CODE
        ]
      );

      console.log(
        "Existing portal access credentials updated."
      );
    } else {
      await pool.query(
        `
          INSERT INTO portal_access_settings (
            organisation_code,
            password_hash,
            is_active,
            valid_from,
            valid_until
          )
          VALUES (?, ?, TRUE, NOW(), ?)
        `,
        [
          ORGANISATION_CODE,
          passwordHash,
          "2026-12-31 23:59:59"
        ]
      );

      console.log(
        "Portal access credentials created."
      );
    }

    console.log("");
    console.log(
      `Organisation Code: ${ORGANISATION_CODE}`
    );
    console.log(
      `Access Password: ${ACCESS_PASSWORD}`
    );
  } catch (error) {
    console.error(
      "Failed to create portal access:",
      error
    );

    process.exitCode = 1;
  } finally {
    await pool.end();
  }
};

createPortalAccess();