import {
  Table as TableModel,
} from '@airtable/blocks/models';

import {
  SerializedAirtableField,
  serializeField
} from './AirtableField';
import {
  AirtableModelAttributes,
  SerializedModelProperties,
} from './AirtableModel';

const SerializedTableProperties = [...SerializedModelProperties, 'name', 'description', 'url', 'primaryField', 'fields'] as const;
type SerializedTableProperties = typeof SerializedTableProperties[number];

export type SerializedAirtableTable = Omit<AirtableModelAttributes<TableModel, SerializedTableProperties>, 'fields'> & {
  fields: SerializedAirtableField[];
};

export function serializeTable(airtableTable: TableModel): SerializedAirtableTable {
  return SerializedTableProperties.reduce((accum:any, propertyName:SerializedTableProperties) => {
    if (propertyName === 'fields') {
      accum['fields'] = airtableTable['fields'].map(field => serializeField(field));
      return accum;
    }

    if (propertyName === 'primaryField') {
      accum[propertyName] = serializeField(airtableTable[propertyName]);
      return accum;
    }

    accum[propertyName] = airtableTable[propertyName];

    return accum;
  }, {} as SerializedAirtableTable);
}