<?php

namespace Modules\ClinicCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\ClinicCore\Entities\ClcPatient;
use Modules\ClinicCore\Entities\Services\PatientMergeService;

/**
 * SIFA P3-T1 — patient duplicate review + merge. Permission-gated on
 * clinic.patient.merge; every query is business_id-scoped.
 */
class ClcPatientMergeController extends Controller
{
    private function businessId(): int
    {
        return (int) request()->session()->get('user.business_id');
    }

    private function guard(): void
    {
        if (!auth()->user()->can('clinic.patient.merge')) {
            abort(403, 'Unauthorized action.');
        }
    }

    /** Duplicates review screen: candidate pairs + review/merge action. */
    public function index(PatientMergeService $svc)
    {
        $this->guard();

        $pairs = $svc->findDuplicates($this->businessId());

        return view('clinicCore::patients.duplicates', compact('pairs'));
    }

    /** Execute a merge (duplicate → master). */
    public function merge(Request $request, PatientMergeService $svc)
    {
        $this->guard();

        $data = $request->validate([
            'master_id'    => 'required|integer',
            'duplicate_id' => 'required|integer|different:master_id',
        ]);

        try {
            $log = $svc->merge(
                (int) $data['master_id'],
                (int) $data['duplicate_id'],
                (int) auth()->id(),
                $this->businessId()
            );
        } catch (\Throwable $e) {
            return response()->json([
                'success' => false,
                'msg'     => $e->getMessage(),
            ], 422);
        }

        return response()->json([
            'success' => true,
            'msg'     => __('clinicCore::lang.patients_merged'),
            'log_id'  => $log->id,
        ]);
    }
}
