
struct PageLinkCommand: CommandProcessor {

    static let commandType: CommandType = .pageLink

    let content: Content

    let results: PageGenerationResults

    let language: ContentLanguage

    init(content: Content, results: PageGenerationResults, language: ContentLanguage) {
        self.content = content
        self.results = results
        self.language = language
    }

    /**
     Format: `![page](<pageId>)`
     */
    func process(_ arguments: [String], markdown: Substring) -> String {
        guard arguments.count == 1 else {
            invalid(markdown)
            return ""
        }
        let pageId = arguments[0]

        guard let page = content.page(pageId) else {
            results.missing(page: pageId, source: "Page link command")
            return ""
        }
        guard !page.isDraft else {
            // Prevent linking to unpublished content
            return ""
        }

        results.linked(to: page)

        let localized = page.localized(in: language)
        let url = page.absoluteUrl(in: language)
        let title = localized.linkPreview.title ?? localized.title
        let description = localized.linkPreview.description ?? ""
        let image = localized.linkPreview.image.map {
            let size = content.settings.pages.pageLinkImageSize
            let imageSet = $0.imageSet(width: size, height: size, language: language)
            results.require(imageSet: imageSet)
            return imageSet
        }

        return RelatedPageLink(
            title: title,
            description: description,
            url: url,
            image: image)
            .content
    }
}
