<?php

namespace App\Services\Tracking;

final class HashedUser
{
    public function __construct(
        public readonly ?string $emailSha256 = null,
        public readonly ?string $phoneSha256 = null,
        public readonly ?string $firstNameSha256 = null,
        public readonly ?string $lastNameSha256 = null,
        public readonly ?string $countrySha256 = null,
        public readonly ?string $ipAddress = null,    // raw — providers hash if spec requires
        public readonly ?string $userAgent = null,
        public readonly ?string $fbc = null,           // Meta _fbc cookie
        public readonly ?string $fbp = null,           // Meta _fbp cookie
        public readonly ?string $ttclid = null,        // TikTok click ID
        public readonly ?string $gclid = null,         // Google Ads click ID
        public readonly ?string $gaClientId = null,    // GA4 _ga cookie client ID
    ) {}

    public static function fromRaw(
        ?string $email = null,
        ?string $phone = null,
        ?string $firstName = null,
        ?string $lastName = null,
        ?string $country = null,
        ?string $ipAddress = null,
        ?string $userAgent = null,
        ?string $fbc = null,
        ?string $fbp = null,
        ?string $ttclid = null,
        ?string $gclid = null,
        ?string $gaClientId = null,
    ): self {
        return new self(
            emailSha256: self::hashEmail($email),
            phoneSha256: self::hashPhone($phone),
            firstNameSha256: self::hashText($firstName),
            lastNameSha256: self::hashText($lastName),
            countrySha256: self::hashText($country),
            ipAddress: $ipAddress,
            userAgent: $userAgent,
            fbc: $fbc,
            fbp: $fbp,
            ttclid: $ttclid,
            gclid: $gclid,
            gaClientId: $gaClientId,
        );
    }

    private static function hashEmail(?string $email): ?string
    {
        if ($email === null || trim($email) === '') return null;
        return hash('sha256', strtolower(trim($email)));
    }

    private static function hashPhone(?string $phone): ?string
    {
        if ($phone === null || trim($phone) === '') return null;
        $digits = preg_replace('/\D+/', '', $phone);
        if ($digits === '') return null;
        return hash('sha256', $digits);
    }

    private static function hashText(?string $text): ?string
    {
        if ($text === null || trim($text) === '') return null;
        return hash('sha256', strtolower(trim($text)));
    }

    /**
     * Build from a Laravel request + optional authenticated client.
     * Reads cookies (_fbc, _fbp, ttclid, _gcl_aw, _ga).
     */
    public static function fromRequest(\Illuminate\Http\Request $request, $client = null): self
    {
        return self::fromRaw(
            email: $client->email ?? null,
            phone: $client->phone ?? null,
            firstName: $client->first_name ?? $client->firstname ?? null,
            lastName: $client->last_name ?? $client->lastname ?? null,
            country: $client->country ?? null,
            ipAddress: $request->ip(),
            userAgent: $request->userAgent(),
            fbc: $request->cookie('_fbc'),
            fbp: $request->cookie('_fbp'),
            ttclid: $request->cookie('ttclid'),
            gclid: $request->cookie('_gcl_aw'),
            gaClientId: self::extractGaClientId($request->cookie('_ga')),
        );
    }

    /**
     * _ga cookie format: GA1.2.1234567890.1601234567 — client id is the numeric part.
     */
    private static function extractGaClientId(?string $gaCookie): ?string
    {
        if (!$gaCookie) return null;
        $parts = explode('.', $gaCookie);
        if (count($parts) < 4) return null;
        return $parts[2] . '.' . $parts[3];
    }
}
