import Foundation
import ForgejoKit
import Testing
@testable import Forji

struct MarkdownComponentsTests {

    private func attachment(name: String, type: String?) -> ForgejoKit.Attachment {
        ForgejoKit.Attachment(
            id: 1, uuid: "u", name: name, size: 0,
            browserDownloadUrl: "https://example.com/a/\(name)",
            type: type, created: Date(),
        )
    }

    // MARK: - attachmentMarkdown

    @Test func imageAttachmentUsesEmbedSyntax() {
        let md = attachmentMarkdown(for: attachment(name: "shot.png", type: "image/png"))
        #expect(md == "![shot.png](https://example.com/a/shot.png)")
    }

    @Test func imageDetectedByExtensionUsesEmbedSyntax() {
        // Forgejo returns the generic type "attachment", so detection falls to the extension.
        let md = attachmentMarkdown(for: attachment(name: "photo.jpg", type: "attachment"))
        #expect(md == "![photo.jpg](https://example.com/a/photo.jpg)")
    }

    @Test func nonImageFileUsesLinkSyntax() {
        let md = attachmentMarkdown(for: attachment(name: "server.log", type: "text/plain"))
        #expect(md == "[server.log](https://example.com/a/server.log)")
    }

    @Test func nonImageBinaryUsesLinkSyntax() {
        let md = attachmentMarkdown(for: attachment(name: "report.pdf", type: "attachment"))
        #expect(md == "[report.pdf](https://example.com/a/report.pdf)")
    }

    // MARK: - repoRelativePath

    @Test func repoRelativePathExtractsFilePath() {
        let url = URL(string: "https://forgejo.example.com/owner/repo/src/branch/main/path/to/file.swift")!
        #expect(repoRelativePath(from: url) == "path/to/file.swift")
    }

    @Test func repoRelativePathReturnsNilForBranchOnly() {
        // URL ends right after the ref, no file path follows
        let url = URL(string: "https://forgejo.example.com/owner/repo/src/branch/main")!
        #expect(repoRelativePath(from: url) == nil)
    }

    @Test func repoRelativePathReturnsNilForUnrelatedURL() {
        let url = URL(string: "https://example.com/some/other/page")!
        #expect(repoRelativePath(from: url) == nil)
    }

    @Test func repoRelativePathHandlesSubpath() {
        let url = URL(string: "https://example.com/forgejo/owner/repo/src/branch/main/README.md")!
        #expect(repoRelativePath(from: url) == "README.md")
    }

    @Test func repoRelativePathHandlesNestedFilePath() {
        let url = URL(string: "https://forgejo.example.com/owner/repo/src/branch/feature/a/b/c.txt")!
        #expect(repoRelativePath(from: url) == "a/b/c.txt")
    }
}
