import Foundation
import GenAPI

public struct Workspace: Equatable, Identifiable {
    public let id: String
    public let name: String
    public let description: String
    public let clipCount: Int
    public let createdAt: Date?
    public let lastUpdatedClip: Date?
    public let ownerId: String?
    public let shared: Bool
    
    public init(
        id: String,
        name: String,
        description: String,
        clipCount: Int,
        createdAt: Date?,
        lastUpdatedClip: Date?,
        ownerId: String?,
        shared: Bool
    ) {
        self.id = id
        self.name = name
        self.description = description
        self.clipCount = clipCount
        self.createdAt = createdAt
        self.lastUpdatedClip = lastUpdatedClip
        self.ownerId = ownerId
        self.shared = shared
    }
    
    public init(_ remote: GenAPI.ProjectMetadataSchema) throws {
        let id = remote.id.string ?? remote.id.uuid?.uuidString
        guard let id else {
            throw DecodingError.valueNotFound(
                String.self,
                .init(codingPath: [], debugDescription: "Missing workspace id")
            )
        }
        
        self.id = id
        self.name = remote.name
        self.description = remote.description
        self.clipCount = remote.clipCount
        self.createdAt = remote.createdAt
        self.lastUpdatedClip = remote.lastUpdatedClip
        self.ownerId = remote.owner?.userId.uuidString
        self.shared = remote.shared
    }
}

public struct WorkspacesPage: Equatable {
    public let currentPage: Int
    public let totalResults: Int
    public let workspaces: [Workspace]
    
    public init(currentPage: Int, totalResults: Int, workspaces: [Workspace]) {
        self.currentPage = currentPage
        self.totalResults = totalResults
        self.workspaces = workspaces
    }
    
    public init(_ remote: GenAPI.ProjectsSchema) throws {
        self.currentPage = remote.currentPage
        self.totalResults = remote.numTotalResults
        self.workspaces = try remote.projects.map { try Workspace($0) }
    }
}

