// Data-import DOMAIN — Direct Upload guards/validators (pure). Source: data-import-spec.md §3.
// These are the testable predicates the reducer + the application use-case consult.

import { isAcceptedForType } from '../formats';
import { supportsGroupByStudy, type DataType } from '../dataTypes';
import { mapFilesToTasks } from '../mapping/fileToTask';
import { validateMhdCompanions } from '../mapping/mhdCompanions';
import { importError, type ImportError } from '../types';
import type { DirectContext } from './states';

/** D2 / MAP3 — Group by Study may be toggled only when a DICOM/NIfTI type is selected. */
export function canToggleGroupByStudy(ctx: DirectContext): boolean {
  return ctx.dataType !== null && supportsGroupByStudy(ctx.dataType);
}

/**
 * Validate staged files before upload (the §3 Validating step). Returns the full list of blocking
 * errors; an empty array means VALIDATE_OK. Enforces:
 *   • D4 (structure) — at least one file, and the §5 mapping yields ≥1 Task.
 *   • D3 (format)    — every file matches the chosen type's accepted set.
 *   • D6 (companions)— every .mhd has its raw companion.
 */
export function validateDirectStaging(ctx: DirectContext): ImportError[] {
  const errors: ImportError[] = [];
  const dataType = ctx.dataType;

  if (dataType === null) {
    errors.push(importError('INVALID_STRUCTURE', 'Chưa chọn loại dữ liệu.'));
    return errors;
  }
  if (ctx.files.length === 0) {
    errors.push(importError('INVALID_STRUCTURE', 'Chưa có tệp nào được chọn.'));
    return errors;
  }

  // D3 — format per chosen type.
  for (const f of ctx.files) {
    if (!isAcceptedForType(dataType, f.name)) {
      errors.push(
        importError('UNSUPPORTED_FORMAT', `Tệp "${f.name}" không đúng định dạng cho loại ${dataType}.`, {
          file: f.relativePath,
        }),
      );
    }
  }

  // D6 — MHD companions.
  errors.push(...validateMhdCompanions(ctx.files));

  // D4 — structural sanity: the mapping must produce at least one Task.
  if (mapFilesToTasks(dataType as DataType, ctx.groupByStudy, ctx.files).length === 0) {
    errors.push(importError('INVALID_STRUCTURE', 'Cấu trúc tệp không tạo được tác vụ nào.'));
  }

  return errors;
}
