import { defineCellType } from '../../types';
import { ReferenceView } from './View';
import { ReferenceEdit } from './Edit';
import { ReferenceEditWrapper } from './ReferenceEditWrapper';

export { ReferenceView, ReferenceEdit };
export type { ReferenceItem, RefSchema, ReferenceTypeConfig } from './types';

type ReferenceValue = Record<string, unknown> | null;

export const referenceCellType = defineCellType<ReferenceValue>({
  type: 'reference',
  ViewComponent: ReferenceView,
  EditComponent: ReferenceEdit,
  EditWrapper: ReferenceEditWrapper,
  serialize: (value) => (value ? JSON.stringify(value) : ''),
  deserialize: (raw) => {
    if (!raw) {
      return null;
    }
    try {
      const parsed = JSON.parse(raw);
      if (parsed && typeof parsed === 'object') {
        return parsed;
      }
    } catch {}
    return null;
  },
  editable: true,
  clearable: true,
  onTypeToEdit: () => ({}),
});
