<?php

namespace App\Domain\Identity\Services;

use App\Domain\Identity\DTOs\NationalIdData;
use App\Domain\Identity\Models\Person;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class PersonService
{
    public function __construct(
        private readonly NationalIdService $nationalIdService,
    ) {}

    public function create(array $data, User $actor): Person
    {
        return DB::transaction(function () use ($data, $actor) {
            // Parse national ID if provided
            if (!empty($data['national_id'])) {
                $parsed = $this->nationalIdService->parse($data['national_id']);
                if ($parsed) {
                    $data['date_of_birth'] = $data['date_of_birth'] ?? $parsed->birthDate->toDateString();
                    $data['gender'] = $data['gender'] ?? $parsed->gender;
                    $data['governorate'] = $data['governorate'] ?? $parsed->governorate;
                }
            }

            $data['created_by'] = $actor->id;

            return Person::create($data);
        });
    }

    public function update(Person $person, array $data, User $actor): Person
    {
        return DB::transaction(function () use ($person, $data) {
            // Re-parse national ID if changed
            if (!empty($data['national_id']) && $data['national_id'] !== $person->national_id) {
                $parsed = $this->nationalIdService->parse($data['national_id']);
                if ($parsed) {
                    $data['date_of_birth'] = $data['date_of_birth'] ?? $parsed->birthDate->toDateString();
                    $data['gender'] = $data['gender'] ?? $parsed->gender;
                    $data['governorate'] = $data['governorate'] ?? $parsed->governorate;
                }
            }

            $person->update($data);
            return $person->fresh();
        });
    }

    public function linkUser(Person $person, User $user): Person
    {
        $person->update(['user_id' => $user->id]);
        $user->update(['person_id' => $person->id]);
        return $person->fresh();
    }
}
