import type { ApplicationFormState, InitiativeFormState } from './initiativeFormTypes';
import {
  INITIAL_APPLICATION_FORM_STATE,
  INITIAL_REPORT_FORM_STATE,
} from './initiativeFormTypes';

/** MinIO evidence kinds for Đơn (2.1 / 2.2 / kỹ thuật) — used when re-fetching a file from the server. */
export type ServerEvidenceKind = 'research' | 'textbook' | 'technical';

/** A pointer to a file stored in IndexedDB under the same draftId. */
export interface FileHandle {
  key: string;
  name: string;
  size: number;
  type: string;
  lastModified: number;
  /** S3/MinIO object key after a successful server upload (optional). */
  serverStorageKey?: string;
  serverUploadedAt?: string;
  /** For restoring downloads when IndexedDB is empty. */
  serverKind?: ServerEvidenceKind;
}

/** Stored version of ApplicationFormState — File replaced by FileHandle. */
export type StoredApplicationForm = Omit<
  ApplicationFormState,
  'textbookEvidenceFile' | 'researchEvidenceFile' | 'technicalEvidenceFile'
> & {
  textbookEvidenceFile: FileHandle | null;
  researchEvidenceFile: FileHandle | null;
  technicalEvidenceFile: FileHandle | null;
};

export interface InitiativeDraft {
  draftId: string;
  version: 1;
  updatedAt: string;
  application: StoredApplicationForm;
  report: InitiativeFormState;
}

export const LS_KEY = 'initiativeDraft.v1';

export function storedApplicationFromInitial(): StoredApplicationForm {
  const a = INITIAL_APPLICATION_FORM_STATE;
  return {
    ...a,
    textbookEvidenceFile: null,
    researchEvidenceFile: null,
    technicalEvidenceFile: null,
  };
}

export function emptyInitiativeDraft(draftId: string): InitiativeDraft {
  return {
    draftId,
    version: 1,
    updatedAt: new Date().toISOString(),
    application: storedApplicationFromInitial(),
    report: { ...INITIAL_REPORT_FORM_STATE },
  };
}
