<?php

namespace App\Services\DecisionEvents\Handlers;

use App\Services\DecisionEvents\Contracts\DecisionEventHandler;
use App\Services\DecisionEvents\DecisionEventContext;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

class AddSegmentHandler implements DecisionEventHandler
{
    public function handle(DecisionEventContext $context, array $config = []): void
    {
        $contract = $context->contract;
        if (! $contract) {
            // If no contract on activity, nothing to apply
            return;
        }

        $segmentId = (int) ($config['segment_id'] ?? 0);
        if ($segmentId <= 0) {
            throw new InvalidArgumentException('add_segment requires a valid segment_id');
        }

        $deactivatePrevious = array_key_exists('deactivate_previous', $config)
            ? (bool) $config['deactivate_previous']
            : true;

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

            // Ensure pivot exists and mark active=1
            $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(),
                ]);
            }
        });
    }
}
