const postgres = require("postgres");

const DEFAULT_DEPARTMENTS = [
  [
    "HR",
    "Human Resources",
    "People operations, recruitment, and employee relations.",
  ],
  [
    "QA",
    "Quality Assurance",
    "Quality systems, audits, and compliance oversight.",
  ],
  ["PRD", "Production", "Manufacturing, operations, and production planning."],
  [
    "ENG",
    "Engineering",
    "Technical development, maintenance, and process improvement.",
  ],
  [
    "LOG",
    "Logistics",
    "Warehouse, shipping, receiving, and inventory coordination.",
  ],
  ["FIN", "Finance", "Accounting, budgeting, and financial control."],
];

const DEFAULT_POSITIONS = [
  ["MGR", "Manager", "Leads team execution, planning, and performance."],
  ["SUP", "Supervisor", "Oversees day-to-day operations and frontline staff."],
  [
    "SNR",
    "Senior Staff",
    "Experienced individual contributor with advanced responsibility.",
  ],
  [
    "STF",
    "Staff",
    "Core contributor responsible for standard operational work.",
  ],
  ["JNR", "Junior Staff", "Entry-level contributor working under guidance."],
  ["TRN", "Trainee", "Newly onboarded employee in structured training period."],
];

async function main() {
  const connectionString = process.env.DATABASE_URL?.trim();

  if (!connectionString) {
    throw new Error("DATABASE_URL is required");
  }

  const sql = postgres(connectionString, { prepare: false });

  try {
    const organizations = await sql`
      select id, name
      from organizations
      order by created_at asc
    `;

    for (const organization of organizations) {
      for (const [code, name, description] of DEFAULT_DEPARTMENTS) {
        await sql`
          insert into departments (organization_id, code, name, description)
          values (${organization.id}, ${code}, ${name}, ${description})
          on conflict (organization_id, name) do nothing
        `;
      }

      for (const [code, name, description] of DEFAULT_POSITIONS) {
        await sql`
          insert into positions (organization_id, code, name, description)
          values (${organization.id}, ${code}, ${name}, ${description})
          on conflict (organization_id, name) do nothing
        `;
      }
    }

    console.log(
      `Seeded master data for ${organizations.length} organization(s).`,
    );
  } finally {
    await sql.end({ timeout: 1 });
  }
}

main().catch((error) => {
  console.error("Failed to seed master data.", error);
  process.exitCode = 1;
});
