import 'server-only';

import { hashPreviewPayload, getEnvironmentBlockers, validateConfirmationToken, withToken } from './reset-guards';
import { getConfirmationPhrase, RESEED_TARGETS } from './reset-scopes';
import type { ReseedExecuteReport, ReseedPreviewReport, ReseedTarget } from './reset-report';

export interface ReseedPreviewInput {
  target: ReseedTarget;
  manifestId?: string | null;
  options?: {
    force?: boolean;
  };
}

export interface ReseedExecuteInput extends ReseedPreviewInput {
  previewHash: string;
  confirmationToken: string;
  confirmationPhrase: string;
  actorId: string;
}

function isReseedTarget(value: string): value is ReseedTarget {
  return RESEED_TARGETS.includes(value as ReseedTarget);
}

export async function previewReseed(input: ReseedPreviewInput): Promise<ReseedPreviewReport> {
  if (!isReseedTarget(input.target)) {
    throw new Error('Unsupported reseed target.');
  }

  const warnings: string[] = [];
  const errors = getEnvironmentBlockers();
  const actions: ReseedPreviewReport['actions'] = [];

  if (input.target === 'foundation') {
    actions.push({
      key: 'foundation',
      status: 'warning',
      message: 'Foundation reseed should run through existing seed services; API execution is blocked until service wrappers are extracted.'
    });
    warnings.push('Foundation reseed is preview-only in D.7.7 to avoid duplicating seed data behavior.');
  }

  if (input.target === 'demo_uat') {
    actions.push({
      key: 'demo_uat',
      status: 'warning',
      message: 'Demo/UAT reseed is deterministic through existing scripts, but API execution is blocked until UAT ownership markers are available.'
    });
    warnings.push('Demo/UAT reseed is preview-only in D.7.7.');
  }

  if (input.target === 'csv_manifest') {
    actions.push({
      key: 'csv_manifest',
      status: 'blocked',
      message: 'CSV manifest reseed requires original CSV files or persisted seed package inputs, which are not stored by D.7.8.'
    });
    errors.push('CSV manifest reseed is blocked because original CSV payloads are not persisted.');
  }

  const previewHash = hashPreviewPayload({
    target: input.target,
    manifestId: input.manifestId ?? null,
    actions,
    warnings,
    errors
  });

  return withToken<ReseedPreviewReport>({
    target: input.target,
    summary: {
      actions: actions.length,
      warnings: warnings.length,
      errors: errors.length
    },
    actions,
    warnings,
    errors,
    confirmationPhrase: getConfirmationPhrase({
      target: input.target,
      manifestId: input.manifestId ?? null
    }),
    previewHash
  });
}

export async function executeReseed(input: ReseedExecuteInput): Promise<ReseedExecuteReport> {
  const preview = await previewReseed(input);
  const tokenError = validateConfirmationToken({
    token: input.confirmationToken,
    kind: 'reseed',
    target: input.target,
    previewHash: input.previewHash
  });
  const errors = [...preview.errors];

  if (preview.previewHash !== input.previewHash) errors.push('Preview hash mismatch. Re-run reseed preview.');
  if (tokenError) errors.push(tokenError);
  if (input.confirmationPhrase !== preview.confirmationPhrase) {
    errors.push('Typed confirmation phrase does not match preview.');
  }

  return {
    ...preview,
    errors: errors.length > 0 ? errors : ['Reseed execution is blocked until safe service wrappers are available.'],
    summary: {
      ...preview.summary,
      errors: errors.length > 0 ? errors.length : preview.summary.errors + 1
    },
    executedAt: new Date().toISOString(),
    executed: false
  };
}
