<?php

/**
 * 文件功能：协议离婚申请通知事件（广播至对方私人频道）
 *
 * 触发时机：一方申请协议离婚后广播，对方收到 Banner 含确认/拒绝按钮。
 *
 * @author  ChatRoom Laravel
 *
 * @version 1.0.0
 */

namespace App\Events;

use App\Models\Marriage;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class MarriageDivorceRequested implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * @param  Marriage  $marriage  婚姻记录
     */
    public function __construct(
        public readonly Marriage $marriage,
    ) {}

    /**
     * 广播至对方私人频道（divorcer 的对方）。
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        // 离婚申请方的对方
        $targetId = $this->marriage->user_id === $this->marriage->divorcer_id
            ? $this->marriage->partner_id
            : $this->marriage->user_id;

        return [new PrivateChannel('user.'.$targetId)];
    }

    /**
     * @return array<string, mixed>
     */
    public function broadcastWith(): array
    {
        $this->marriage->load(['user:id,username', 'partner:id,username']);

        $divorcerUsername = $this->marriage->user_id === $this->marriage->divorcer_id
            ? $this->marriage->user?->username
            : $this->marriage->partner?->username;

        // 读取协议离婚魅力惩罚供前端展示
        $penalty = (int) \App\Models\MarriageConfig::where('key', 'divorce_mutual_charm')->value('value');
        // 读取强制离婚魅力惩罚（被拒=强制离婚时申请方受此惩罚）
        $forcedPenalty = (int) \App\Models\MarriageConfig::where('key', 'divorce_forced_charm')->value('value');

        return [
            'marriage_id' => $this->marriage->id,
            'divorcer_username' => $divorcerUsername,
            'initiator_name' => $divorcerUsername,  // 前端兼容字段
            'timeout_hours' => 72,
            'requested_at' => $this->marriage->divorce_requested_at,
            'mutual_charm_penalty' => $penalty,           // 协议离婚双方各扣魅力
            'forced_charm_penalty' => $forcedPenalty,     // 不同意→强制，申请方受此惩罚
        ];
    }

    /** 广播事件名称。 */
    public function broadcastAs(): string
    {
        return 'marriage.divorce_requested';
    }
}
