# frozen_string_literal: true

require 'securerandom'
require 'sequel'
require 'json'
require 'time'
require_relative '../config/database'

Database.connection

# 升级记录模型
class UpgradeRecord < Sequel::Model(:upgrade_records)
  plugin :timestamps, update_on_create: true
  plugin :validation_helpers
  plugin :json_serializer
  plugin :serialization

  # JSON序列化字段
  serialize_attributes :json, :deployment_result, :file_results

  # 状态枚举
  STATUS_ENUM = {
    'pending' => '待部署',
    'deploying' => '部署中',
    'success' => '成功',
    'partial' => '部分成功',
    'failed' => '失败'
  }.freeze

  # 验证
  def validate
    super
    validates_presence :package_name
  end

  # 状态文本
  def status_text
    STATUS_ENUM[status] || status
  end

  # 开始部署
  def start_deployment!
    self.status = 'deploying'
    self.started_at = Time.now
    save
  end

  # 完成部署
  def complete_deployment!(success:, result: nil, file_results: nil)
    self.status = success ? 'success' : (file_results && file_results.any? { |r| r[:status] == 'success' }) ? 'partial' : 'failed'
    self.completed_at = Time.now
    self.deployment_result = result if result
    self.file_results = file_results if file_results
    save
  end

  # 转换为API响应格式
  def to_api_hash
    {
      id: id,
      package_name: package_name,
      package_version: package_version,
      status: status,
      status_text: status_text,
      deployment_result: deployment_result,
      file_results: file_results,
      started_at: started_at&.iso8601,
      completed_at: completed_at&.iso8601,
      created_at: created_at&.iso8601
    }
  end
end
