<?php

namespace App\Listeners;

use App\Events\ChangeContractSegment;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;

class ApplyChangeContractSegment implements ShouldQueue
{
    public function handle(ChangeContractSegment $event): void
    {
        $contract = $event->contract;
        $segmentId = (int) $event->segmentId;
        if ($segmentId <= 0) {
            return;
        }

        DB::transaction(function () use ($contract, $segmentId, $event) {
            if ($event->deactivatePrevious) {
                DB::table('contract_segment')
                    ->where('contract_id', $contract->id)
                    ->where('active', 1)
                    ->update(['active' => 0, 'updated_at' => now()]);
            }

            $existing = DB::table('contract_segment')
                ->where('contract_id', $contract->id)
                ->where('segment_id', $segmentId)
                ->first();

            if ($existing) {
                DB::table('contract_segment')
                    ->where('id', $existing->id)
                    ->update(['active' => 1, 'updated_at' => now()]);
            } else {
                DB::table('contract_segment')->insert([
                    'contract_id' => $contract->id,
                    'segment_id' => $segmentId,
                    'active' => 1,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        });
    }
}
