/**
 * Ensure GM position has all module permissions.
 * Adds any missing permissions for: contacts, crm, inventory, projects, hr, marketing, admin
 */
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const GM_MODULES = ['contacts', 'crm', 'inventory', 'projects', 'hr', 'marketing', 'admin'];

async function main() {
  const gmPosition = await prisma.position.findFirst({ where: { code: 'GM' } });
  if (!gmPosition) {
    console.log('GM position not found.');
    process.exit(1);
  }

  const existing = await prisma.positionPermission.findMany({
    where: { positionId: gmPosition.id },
    select: { module: true },
  });
  const existingModules = new Set(existing.map((p) => p.module));

  let added = 0;
  for (const module of GM_MODULES) {
    if (existingModules.has(module)) continue;
    await prisma.positionPermission.create({
      data: {
        positionId: gmPosition.id,
        module,
        resource: '*',
        actions: ['*'],
      },
    });
    console.log(`Added permission: ${module}`);
    added++;
  }

  if (added === 0) {
    console.log('All GM permissions already exist.');
  } else {
    console.log(`Added ${added} permission(s).`);
  }
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(() => prisma.$disconnect());
