<?php

namespace GriffinForms\Includes\Integrations\Mailchimp;

class IdentityStore
{
    public function buildOwnerContext(int $submission_id, int $form_id, int $user_id): array
    {
        return [
            'submission_id' => $submission_id > 0 ? $submission_id : 0,
            'form_id' => $form_id > 0 ? $form_id : 0,
            'wordpress_user_id' => $user_id > 0 ? $user_id : 0,
            'owner_model' => $user_id > 0 ? 'submission_plus_user' : 'submission_only',
        ];
    }

    public function buildIdentityRecord(int $submission_id, int $form_id, int $user_id, string $audience_id, string $email, string $subscriber_hash): array
    {
        $audience_id = sanitize_text_field($audience_id);
        $email = sanitize_email($email);
        $subscriber_hash = sanitize_text_field($subscriber_hash);
        $identity_key = '';

        if ($audience_id !== '' && $subscriber_hash !== '') {
            $identity_key = sha1(implode('|', [
                Contract::INTEGRATION_ID,
                $audience_id,
                $subscriber_hash,
            ]));
        }

        return [
            'schema_version' => Contract::IDENTITY_SCHEMA_VERSION,
            'provider' => Contract::INTEGRATION_ID,
            'provider_entity' => 'subscriber',
            'identity_key' => $identity_key,
            'audience_id' => $audience_id,
            'subscriber_hash' => $subscriber_hash,
            'normalized_email' => $email,
            'owner' => $this->buildOwnerContext($submission_id, $form_id, $user_id),
            'storage_strategy' => [
                'canonical' => 'submission_meta',
                'user_indexed' => $user_id > 0,
                'dedicated_record' => false,
            ],
        ];
    }

    public function getUserIdentities(int $user_id): array
    {
        if ($user_id <= 0) {
            return [];
        }

        $raw = get_user_meta($user_id, Contract::USER_META_IDENTITIES, true);
        return is_array($raw) ? $raw : [];
    }

    public function persistUserIdentity(int $user_id, array $identity, array $sync_state): bool
    {
        if ($user_id <= 0) {
            return false;
        }

        $identity_key = sanitize_text_field((string) ($identity['identity_key'] ?? ''));
        $audience_id = sanitize_text_field((string) ($identity['audience_id'] ?? ''));
        $subscriber_hash = sanitize_text_field((string) ($identity['subscriber_hash'] ?? ''));
        $normalized_email = sanitize_email((string) ($identity['normalized_email'] ?? ''));
        if ($identity_key === '' || $audience_id === '' || $subscriber_hash === '' || $normalized_email === '') {
            return false;
        }

        $identities = $this->getUserIdentities($user_id);
        $existing = isset($identities[$identity_key]) && is_array($identities[$identity_key])
            ? $identities[$identity_key]
            : [];
        $now = gmdate('c');

        $identities[$identity_key] = array_replace($existing, [
            'schema_version' => Contract::IDENTITY_SCHEMA_VERSION,
            'provider' => Contract::INTEGRATION_ID,
            'provider_entity' => 'subscriber',
            'identity_key' => $identity_key,
            'audience_id' => $audience_id,
            'subscriber_hash' => $subscriber_hash,
            'normalized_email' => $normalized_email,
            'wordpress_user_id' => $user_id,
            'first_submission_id' => isset($existing['first_submission_id']) ? (int) $existing['first_submission_id'] : (int) ($identity['owner']['submission_id'] ?? 0),
            'last_submission_id' => (int) ($identity['owner']['submission_id'] ?? 0),
            'first_form_id' => isset($existing['first_form_id']) ? (int) $existing['first_form_id'] : (int) ($identity['owner']['form_id'] ?? 0),
            'last_form_id' => (int) ($identity['owner']['form_id'] ?? 0),
            'first_synced_at' => !empty($existing['first_synced_at']) ? sanitize_text_field((string) $existing['first_synced_at']) : $now,
            'last_synced_at' => $now,
            'last_sync_status' => sanitize_key((string) ($sync_state['status'] ?? '')),
            'last_member_status' => sanitize_key((string) ($sync_state['member_status'] ?? '')),
            'last_identity_owner_model' => sanitize_key((string) ($identity['owner']['owner_model'] ?? 'submission_only')),
        ]);

        return update_user_meta($user_id, Contract::USER_META_IDENTITIES, $identities) !== false;
    }
}
