require "jennifer/model/base"

module ContainerMom::Models
  class ContainerDeployment < Jennifer::Model::Base
    with_timestamps

    mapping(
      id: Primary64,
      user_id: Int64,
      name: String,
      source_type: String,
      source_url: String,
      regions: Array(String),
      cpu: String,
      memory: String,
      status: String,
      error_message: String?,
      created_at: Time?,
      updated_at: Time?
    )

    belongs_to :user, User

    validates_presence :name
    validates_presence :source_type
    validates_presence :source_url
    validates_presence :regions
    validates_presence :cpu
    validates_presence :memory
    validates_presence :status

    validates_inclusion :source_type, ["git", "container"]
    validates_inclusion :status, ["pending", "running", "failed", "stopped"]

    def self.create_for_user(user : User, params : NamedTuple) : ContainerDeployment
      create({
        user_id: user.id,
        name: params[:name],
        source_type: params[:source_type],
        source_url: params[:source_url],
        regions: params[:regions],
        cpu: params[:cpu],
        memory: params[:memory],
        status: "pending",
      })
    end

    def active? : Bool
      status == "running"
    end

    def failed? : Bool
      status == "failed"
    end

    def stopped? : Bool
      status == "stopped"
    end

    def pending? : Bool
      status == "pending"
    end

    def update_status(new_status : String, error : String? = nil) : Bool
      update(
        status: new_status,
        error_message: error
      )
    end
  end
end
