import { makeAutoObservable } from 'mobx';
import type { NewsItem } from '../../api';

export class NewsModel {
  readonly id: string;
  title = '';
  slug = '';
  summary = '';
  content = '';
  imageUrl: string | null = null;
  publishedAt = '';
  status: 'draft' | 'published' | 'archived' = 'draft';

  constructor(dto: NewsItem) {
    this.id = String(dto.id);
    this.hydrate(dto);

    makeAutoObservable(this, { id: false }, { autoBind: true });
  }

  get href() {
    return `/news/${this.slug}`;
  }

  update(dto: Partial<NewsItem>) {
    this.hydrate(dto);
  }

  toJSON(): NewsItem {
    return {
      id: this.id,
      title: this.title,
      slug: this.slug,
      summary: this.summary,
      content: this.content,
      imageUrl: this.imageUrl ?? undefined,
      publishedAt: this.publishedAt,
      status: this.status,
    };
  }

  private hydrate(dto: Partial<NewsItem>) {
    if (dto.title !== undefined) {
      this.title = dto.title;
    }

    if (dto.slug !== undefined) {
      this.slug = dto.slug;
    }

    if (dto.summary !== undefined) {
      this.summary = dto.summary;
    }

    if (dto.content !== undefined) {
      this.content = dto.content;
    }

    if (dto.imageUrl !== undefined) {
      this.imageUrl = dto.imageUrl ?? null;
    }

    if (dto.publishedAt != undefined) {
      this.publishedAt = dto.publishedAt;
    }

    if (dto.status !== undefined) {
      this.status = dto.status as typeof this.status;
    }
  }
}
