import type { Response } from 'express';

/**
 * When the DB was never migrated for organizers (or db push failed), Prisma throws.
 * Return a clear JSON error so operators know to run `prisma migrate deploy`, not `db push`.
 */
export function respondIfOrganizerMigrationNeeded(err: unknown, res: Response): boolean {
  const e = err as {
    code?: string;
    meta?: { modelName?: string; table?: string; column?: string };
    message?: string;
  };
  const msg = String(e?.message ?? '');

  if (e?.code === 'P2021') {
    const model = e.meta?.modelName ?? '';
    const table = e.meta?.table ?? '';
    if (model === 'Organizer' || table.includes('Organizer')) {
      res.status(503).json({
        error:
          'Database is missing the Organizer table. On the server run: cd backend && npm run migrate:deploy (use Prisma migrate, not db push).',
      });
      return true;
    }
  }

  if (e?.code === 'P2022' && (msg.includes('organizerId') || e.meta?.column === 'organizerId')) {
    res.status(503).json({
      error:
        'Database is missing meetup organizer columns. On the server run: cd backend && npm run migrate:deploy (do not use prisma db push for this upgrade).',
    });
    return true;
  }

  return false;
}
