<?php

namespace Kylin\Payment\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * 支付回调日志模型
 */
class PaymentCallbackLog extends Model
{
    /**
     * 表名
     */
    protected $table = 'payment_callback_logs';

    /**
     * 可填充字段
     */
    protected $fillable = [
        'payment_type',
        'out_trade_no',
        'trade_no',
        'method',
        'uri',
        'headers',
        'query',
        'body',
        'ip',
        'user_agent',
        'status',
        'response',
        'error_message',
        'processing_time',
    ];

    /**
     * 类型转换
     */
    protected $casts = [
        'headers' => 'json',
        'query' => 'json',
        'response' => 'json',
        'processing_time' => 'integer',
    ];

    /**
     * 处理状态常量
     */
    const STATUS_PENDING = 'pending';
    const STATUS_SUCCESS = 'success';
    const STATUS_FAILED = 'failed';

    /**
     * 标记为处理成功
     */
    public function markAsSuccess(array $response = [], int $processingTime = 0): bool
    {
        return $this->update([
            'status' => self::STATUS_SUCCESS,
            'response' => $response,
            'processing_time' => $processingTime,
        ]);
    }

    /**
     * 标记为处理失败
     */
    public function markAsFailed(string $errorMessage = '', int $processingTime = 0): bool
    {
        return $this->update([
            'status' => self::STATUS_FAILED,
            'error_message' => $errorMessage,
            'processing_time' => $processingTime,
        ]);
    }

    /**
     * 根据商户订单号查找记录
     */
    public static function findByOutTradeNo(string $outTradeNo, ?string $paymentType = null): ?self
    {
        $query = self::where('out_trade_no', $outTradeNo);

        if ($paymentType) {
            $query->where('payment_type', $paymentType);
        }

        return $query->first();
    }

    /**
     * 根据支付平台订单号查找记录
     */
    public static function findByTradeNo(string $tradeNo, ?string $paymentType = null): ?self
    {
        $query = self::where('trade_no', $tradeNo);

        if ($paymentType) {
            $query->where('payment_type', $paymentType);
        }

        return $query->first();
    }

    /**
     * 获取指定状态的记录
     */
    public static function getByStatus(string $status, array $where = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = self::where('status', $status);

        foreach ($where as $key => $value) {
            $query->where($key, $value);
        }

        return $query;
    }
}
