import Foundation
import SwiftData

/// One chapter of a `Book`. Spanish + English paragraphs are stored as JSON-
/// encoded `[String]` so SwiftData doesn't have to manage variable-length
/// arrays directly.
@Model
public final class BookChapter {
    @Attribute(.unique) public var id: String = ""        // "<bookSlug>-ch<number>"
    public var bookSlug: String = ""
    public var number: Int = 0
    public var title: String = ""
    /// Spanish paragraph count, stored at seed time so chapter lists can show
    /// it without decoding the full `paragraphsESJSON` blob on every render.
    public var paragraphCount: Int = 0
    public var paragraphsESJSON: Data = Data()
    public var paragraphsENJSON: Data = Data()

    public init(
        id: String,
        bookSlug: String,
        number: Int,
        title: String,
        paragraphCount: Int,
        paragraphsESJSON: Data,
        paragraphsENJSON: Data
    ) {
        self.id = id
        self.bookSlug = bookSlug
        self.number = number
        self.title = title
        self.paragraphCount = paragraphCount
        self.paragraphsESJSON = paragraphsESJSON
        self.paragraphsENJSON = paragraphsENJSON
    }

    public func paragraphsES() -> [String] {
        (try? JSONDecoder().decode([String].self, from: paragraphsESJSON)) ?? []
    }

    public func paragraphsEN() -> [String] {
        (try? JSONDecoder().decode([String].self, from: paragraphsENJSON)) ?? []
    }
}
