import Foundation

// All DTO types are explicitly nonisolated to ensure their Decodable conformances
// are not infected by the module-wide @MainActor default isolation, allowing them
// to be decoded freely inside non-MainActor contexts (e.g. actor BookStackAPI).

// MARK: - Shared

nonisolated struct CoverDTO: Codable, Sendable, Hashable {
    let url: String
}

// MARK: - Tag

nonisolated struct TagDTO: Codable, Sendable, Hashable, Identifiable {
    let name: String
    let value: String
    let order: Int

    // Synthesised stable identity: tags have no server-side id in the list endpoint
    var id: String { "\(name):\(value)" }

    enum CodingKeys: String, CodingKey {
        case name, value, order
    }
}

nonisolated struct PaginatedResponse<T: Codable & Sendable>: Codable, Sendable {
    let data: [T]
    let total: Int

    enum CodingKeys: String, CodingKey {
        case data, total
    }
}

// MARK: - Shelf

nonisolated struct ShelfDTO: Codable, Sendable, Identifiable, Hashable {
    let id: Int
    let name: String
    let slug: String
    let description: String
    let createdAt: Date
    let updatedAt: Date
    let cover: CoverDTO?

    enum CodingKeys: String, CodingKey {
        case id, name, slug, description, cover
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

// MARK: - Book

nonisolated struct BookDTO: Codable, Sendable, Identifiable, Hashable {
    let id: Int
    let name: String
    let slug: String
    let description: String
    let createdAt: Date
    let updatedAt: Date
    let cover: CoverDTO?

    enum CodingKeys: String, CodingKey {
        case id, name, slug, description, cover
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

// MARK: - Chapter

nonisolated struct ChapterDTO: Codable, Sendable, Identifiable, Hashable {
    let id: Int
    let bookId: Int
    let name: String
    let slug: String
    let description: String
    let priority: Int
    let createdAt: Date
    let updatedAt: Date

    enum CodingKeys: String, CodingKey {
        case id, name, slug, description, priority
        case bookId = "book_id"
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

// MARK: - Page

nonisolated struct PageDTO: Codable, Sendable, Identifiable, Hashable {
    let id: Int
    let bookId: Int
    let chapterId: Int?
    let name: String
    let slug: String
    let html: String?
    let markdown: String?
    let priority: Int
    let draftStatus: Bool
    let tags: [TagDTO]
    let createdAt: Date
    let updatedAt: Date

    enum CodingKeys: String, CodingKey {
        case id, name, slug, html, markdown, priority, tags
        case bookId = "book_id"
        case chapterId = "chapter_id"
        case draftStatus = "draft"
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }

    init(id: Int, bookId: Int, chapterId: Int?, name: String, slug: String,
         html: String?, markdown: String?, priority: Int, draftStatus: Bool,
         tags: [TagDTO] = [], createdAt: Date, updatedAt: Date) {
        self.id = id; self.bookId = bookId; self.chapterId = chapterId
        self.name = name; self.slug = slug; self.html = html; self.markdown = markdown
        self.priority = priority; self.draftStatus = draftStatus; self.tags = tags
        self.createdAt = createdAt; self.updatedAt = updatedAt
    }

    init(from decoder: Decoder) throws {
        let c = try decoder.container(keyedBy: CodingKeys.self)
        id          = try c.decode(Int.self, forKey: .id)
        bookId      = try c.decode(Int.self, forKey: .bookId)
        chapterId   = try c.decodeIfPresent(Int.self, forKey: .chapterId)
        name        = try c.decode(String.self, forKey: .name)
        slug        = try c.decode(String.self, forKey: .slug)
        html        = try c.decodeIfPresent(String.self, forKey: .html)
        markdown    = try c.decodeIfPresent(String.self, forKey: .markdown)
        priority    = try c.decode(Int.self, forKey: .priority)
        draftStatus = try c.decode(Bool.self, forKey: .draftStatus)
        tags        = (try? c.decodeIfPresent([TagDTO].self, forKey: .tags)) ?? []
        createdAt   = try c.decode(Date.self, forKey: .createdAt)
        updatedAt   = try c.decode(Date.self, forKey: .updatedAt)
    }
}

// MARK: - Search

nonisolated struct SearchResultDTO: Codable, Sendable, Identifiable, Hashable {
    let id: Int
    let name: String
    let slug: String
    let type: ContentType
    let url: String
    let preview: String?
    let tags: [TagDTO]

    init(id: Int, name: String, slug: String, type: ContentType, url: String, preview: String?, tags: [TagDTO] = []) {
        self.id = id; self.name = name; self.slug = slug; self.type = type
        self.url = url; self.preview = preview; self.tags = tags
    }

    init(from decoder: Decoder) throws {
        let c = try decoder.container(keyedBy: CodingKeys.self)
        id      = try c.decode(Int.self, forKey: .id)
        name    = try c.decode(String.self, forKey: .name)
        slug    = try c.decode(String.self, forKey: .slug)
        type    = try c.decode(ContentType.self, forKey: .type)
        url     = try c.decode(String.self, forKey: .url)
        preview = try c.decodeIfPresent(String.self, forKey: .preview)
        tags    = (try? c.decodeIfPresent([TagDTO].self, forKey: .tags)) ?? []
    }

    enum ContentType: String, Codable, Sendable, CaseIterable {
        case page, book, chapter, shelf

        var displayName: String {
            switch self {
            case .page: return NSLocalizedString("search.type.page", comment: "")
            case .book: return NSLocalizedString("search.type.book", comment: "")
            case .chapter: return NSLocalizedString("search.type.chapter", comment: "")
            case .shelf: return NSLocalizedString("search.type.shelf", comment: "")
            }
        }

        var systemImage: String {
            switch self {
            case .page: return "doc.text"
            case .book: return "book.closed"
            case .chapter: return "list.bullet.rectangle"
            case .shelf: return "books.vertical"
            }
        }
    }
}

nonisolated struct SearchResponseDTO: Codable, Sendable {
    let data: [SearchResultDTO]
    let total: Int
}

// MARK: - Tag List (from /api/tags)

nonisolated struct TagListResponseDTO: Codable, Sendable {
    let data: [TagDTO]
    let total: Int
}

// MARK: - Comment

nonisolated struct CommentDTO: Codable, Sendable, Identifiable, Hashable {
    let id: Int
    let html: String
    let pageId: Int
    let createdBy: UserSummaryDTO
    let createdAt: Date
    let updatedAt: Date

    enum CodingKeys: String, CodingKey {
        case id, html
        case pageId = "commentable_id"
        case createdBy = "created_by"
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

/// Minimal shape returned by the list endpoint — only used to get IDs for detail fetches.
nonisolated struct CommentSummaryDTO: Codable, Sendable {
    let id: Int
}

nonisolated struct UserSummaryDTO: Codable, Sendable, Hashable {
    let id: Int
    let name: String
    let avatarUrl: String?

    enum CodingKeys: String, CodingKey {
        case id, name
        case avatarUrl = "avatar_url"
    }
}

// MARK: - API Info (from /api/system)

nonisolated struct APIInfo: Codable, Sendable {
    let version: String
    let appName: String?
    let instanceId: String?
    let baseUrl: String?

    enum CodingKeys: String, CodingKey {
        case version
        case appName = "app_name"
        case instanceId = "instance_id"
        case baseUrl = "base_url"
    }
}

// MARK: - User

nonisolated struct UserDTO: Codable, Sendable {
    let id: Int
    let name: String
    let email: String
    let avatarUrl: String?

    enum CodingKeys: String, CodingKey {
        case id, name, email
        case avatarUrl = "avatar_url"
    }
}

// MARK: - Image Gallery

nonisolated struct ImageUploadResponse: Codable, Sendable {
    let id: Int
    let name: String
    let url: String
    let content: ImageContent?

    nonisolated struct ImageContent: Codable, Sendable {
        let html: String?
        let markdown: String?
    }
}
