-- Add tenders module permissions to all positions that have crm or admin access.
-- Safe to run multiple times (skips if already exists).
-- Run on server: docker-compose exec -T postgres psql -U postgres -d mind14_crm -f - < backend/prisma/add-tenders-permissions.sql
-- Or from backend: npx prisma db execute --file prisma/add-tenders-permissions.sql

-- Tenders resource: read, create, update, delete
INSERT INTO position_permissions (id, "positionId", module, resource, actions, "createdAt", "updatedAt")
SELECT gen_random_uuid(), sub."positionId", 'tenders', 'tenders', '["read","create","update","delete"]'::jsonb, NOW(), NOW()
FROM (
  SELECT DISTINCT pp."positionId" FROM position_permissions pp
  WHERE pp.module IN ('crm', 'admin')
) sub
WHERE NOT EXISTS (
  SELECT 1 FROM position_permissions pp2
  WHERE pp2."positionId" = sub."positionId" AND pp2.module = 'tenders' AND pp2.resource = 'tenders'
);

-- Directives resource: read, create, update
INSERT INTO position_permissions (id, "positionId", module, resource, actions, "createdAt", "updatedAt")
SELECT gen_random_uuid(), sub."positionId", 'tenders', 'directives', '["read","create","update"]'::jsonb, NOW(), NOW()
FROM (
  SELECT DISTINCT pp."positionId" FROM position_permissions pp
  WHERE pp.module IN ('crm', 'admin')
) sub
WHERE NOT EXISTS (
  SELECT 1 FROM position_permissions pp2
  WHERE pp2."positionId" = sub."positionId" AND pp2.module = 'tenders' AND pp2.resource = 'directives'
);
