//
//  Project.swift
//  CheapRetouch
//
//  Project model holding original image reference and operation stack.
//

import Foundation

struct Project: Codable, Identifiable {
    let id: UUID
    var name: String
    var imageSource: ImageSource
    var operations: [EditOperation]
    var currentIndex: Int
    let createdAt: Date
    var modifiedAt: Date

    enum ImageSource: Codable {
        case photoLibrary(localIdentifier: String)
        case embedded(data: Data)
    }

    init(
        id: UUID = UUID(),
        name: String = "Untitled",
        imageSource: ImageSource,
        operations: [EditOperation] = [],
        currentIndex: Int = 0,
        createdAt: Date = Date(),
        modifiedAt: Date = Date()
    ) {
        self.id = id
        self.name = name
        self.imageSource = imageSource
        self.operations = operations
        self.currentIndex = currentIndex
        self.createdAt = createdAt
        self.modifiedAt = modifiedAt
    }

    var canUndo: Bool {
        currentIndex > 0
    }

    var canRedo: Bool {
        currentIndex < operations.count
    }

    mutating func addOperation(_ operation: EditOperation) {
        // Remove any operations after current index (discard redo stack)
        if currentIndex < operations.count {
            operations.removeSubrange(currentIndex..<operations.count)
        }
        operations.append(operation)
        currentIndex = operations.count
        modifiedAt = Date()
    }

    mutating func undo() -> Bool {
        guard canUndo else { return false }
        currentIndex -= 1
        modifiedAt = Date()
        return true
    }

    mutating func redo() -> Bool {
        guard canRedo else { return false }
        currentIndex += 1
        modifiedAt = Date()
        return true
    }

    var activeOperations: [EditOperation] {
        Array(operations.prefix(currentIndex))
    }
}
