import { DuplicateSlugError, PageNotFoundError, PageNotPublishedError } from '../domain/errors.js';
import type { CmsRepository } from '../domain/ports.js';
import type { CreatePageInput, Page, UpdatePageInput } from '../domain/page.js';

export class CmsService {
  constructor(private readonly repo: CmsRepository) {}

  async create(input: CreatePageInput): Promise<Page> {
    const created = await this.repo.create(input);
    if (!created) throw new DuplicateSlugError();
    return created;
  }

  async update(id: string, patch: UpdatePageInput): Promise<Page> {
    const updated = await this.repo.update(id, patch);
    if (!updated) throw new PageNotFoundError();
    return updated;
  }

  async publish(id: string): Promise<Page> {
    const updated = await this.repo.setStatus(id, 'published');
    if (!updated) throw new PageNotFoundError();
    return updated;
  }

  async unpublish(id: string): Promise<Page> {
    const updated = await this.repo.setStatus(id, 'draft');
    if (!updated) throw new PageNotFoundError();
    return updated;
  }

  async getPublicPageBySlug(slug: string): Promise<Page> {
    const page = await this.repo.findBySlug(slug);
    if (!page) throw new PageNotFoundError();
    if (page.status !== 'published') throw new PageNotPublishedError();
    return page;
  }

  async listAll(): Promise<Page[]> {
    return this.repo.listAll();
  }
}
