import { File, type IFile } from '../models/store/File.js'
import { ApiFileKind } from '../models/kinds.js'
import { ApiModel, ApiModelSchema } from './ApiModel.js'

export interface IApiFile extends IFile {
  kind: typeof ApiFileKind
}

/**
 * Used by the store. A file definition for the ApiModel.
 */
export class ApiFile extends File {
  override kind = ApiFileKind

  static override fromName(name: string): ApiFile {
    return super.fromName(name, ApiFileKind) as ApiFile
  }

  /**
   * Creates the file definition for a DomainNamespace contents.
   *
   * @param input The data namespace instance or schema.
   */
  static fromApiModel(input: ApiModel | ApiModelSchema): ApiFile {
    let final: ApiModelSchema
    if (typeof (input as ApiModel).toJSON === 'function') {
      final = (input as ApiModel).toJSON()
    } else {
      final = input as ApiModelSchema
    }
    return new ApiFile({ key: final.key, info: final.info })
  }

  constructor(state: Partial<IApiFile> = {}) {
    super({ ...state, kind: ApiFileKind })
  }

  static isApiFile(input: unknown): boolean {
    const typed = input as IApiFile
    if (!input || typed.kind !== ApiFileKind) {
      return false
    }
    return true
  }

  override toJSON(): IApiFile {
    const result: IApiFile = {
      ...super.toJSON(),
      kind: ApiFileKind,
    }
    return result
  }
}
