import { ForbiddenException, NotFoundException } from '@nestjs/common';
import { Repository } from 'typeorm';
import { ImportRun } from './entities/import-run.entity';
import { ImportStep } from './entities/import-step.entity';
import { IMPORT_STEP_LABELS, IMPORT_STEP_ORDER } from './imports.types';
import type { ImportStepKey } from './imports.types';

export interface ImportPrincipal {
  id: number;
  permissions: string[];
  isSuperAdmin: boolean;
}

const STEP_PERMISSIONS: Record<ImportStepKey, string[]> = {
  students: ['student:import'],
  rooms: ['room:create', 'room:edit'],
  checkins: ['occupancy:checkin'],
  transfers: ['occupancy:transfer'],
};

export async function findOwnedRun(
  runs: Repository<ImportRun>,
  userId: number,
  runId: string,
): Promise<ImportRun> {
  const run = await runs.findOne({ where: { id: runId, userId } });
  if (!run) throw new NotFoundException('导入任务不存在');
  return run;
}

export async function findStep(
  steps: Repository<ImportStep>,
  runId: string,
  stepKey: ImportStepKey,
): Promise<ImportStep | null> {
  return steps.findOne({ where: { runId, stepKey } });
}

export function assertStepPermission(principal: ImportPrincipal, stepKey: ImportStepKey): void {
  if (principal.isSuperAdmin) return;
  const required = STEP_PERMISSIONS[stepKey];
  if (!required.some((code) => principal.permissions.includes(code))) {
    throw new ForbiddenException(
      `权限不足：提交「${IMPORT_STEP_LABELS[stepKey]}」需要 ${required.join(' 或 ')}`,
    );
  }
}

/** Step keys the current principal may actually commit. */
export function permittedStepKeys(principal: ImportPrincipal): ImportStepKey[] {
  if (principal.isSuperAdmin) return [...IMPORT_STEP_ORDER];
  return IMPORT_STEP_ORDER.filter((stepKey) =>
    STEP_PERMISSIONS[stepKey].some((code) => principal.permissions.includes(code)),
  );
}
