<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use App\Support\GeoLocation;
use App\Support\OfferAudience;

class ProviderOffer extends Model
{
    use HasFactory, SoftDeletes;

    protected $guarded = [];

    protected $casts = [
        'steps' => 'array',
        'rewards' => 'array',
        'devices' => 'array',
        'raw_payload' => 'array',
        'is_active' => 'boolean',
        'is_featured' => 'boolean',
        'is_hot' => 'boolean',
        'curation_locked' => 'boolean',
        'last_synced_at' => 'datetime',
    ];

    public function offerwall(): BelongsTo
    {
        return $this->belongsTo(Offerwall::class);
    }

    public function clicks(): HasMany
    {
        return $this->hasMany(OfferwallClick::class);
    }

    public function launchUrlFor(User $user): string
    {
        $url = $this->direct_url ?: optional($this->offerwall)->iframe_url ?: '';
        $replacements = [
            '{user_id}' => $user->id,
            '{USER_ID}' => $user->id,
            '[user_id]' => $user->id,
            '[USER_ID]' => $user->id,
            '{uniqueUserID}' => $user->id,
            '{unique_user_id}' => $user->id,
            '[uniqueUserID]' => $user->id,
            '[unique_user_id]' => $user->id,
            '{uid}' => $user->id,
            '{UID}' => $user->id,
            '[uid]' => $user->id,
            '[UID]' => $user->id,
            '{subid}' => $user->id,
            '{SUBID}' => $user->id,
            '[subid]' => $user->id,
            '[SUBID]' => $user->id,
            '{username}' => rawurlencode($user->username),
            '{USERNAME}' => rawurlencode($user->username),
            '[username]' => rawurlencode($user->username),
            '[USERNAME]' => rawurlencode($user->username),
            '{email}' => rawurlencode($user->email),
            '{EMAIL}' => rawurlencode($user->email),
            '[email]' => rawurlencode($user->email),
            '[EMAIL]' => rawurlencode($user->email),
            '{offer_id}' => rawurlencode((string) $this->provider_offer_id),
            '{OFFER_ID}' => rawurlencode((string) $this->provider_offer_id),
            '[offer_id]' => rawurlencode((string) $this->provider_offer_id),
            '[OFFER_ID]' => rawurlencode((string) $this->provider_offer_id),
            '{country}' => rawurlencode((string) GeoLocation::countryForRequest()),
            '{country_code}' => rawurlencode((string) GeoLocation::countryForRequest()),
            '{os}' => OfferAudience::deviceForRequest(),
            '{device}' => OfferAudience::deviceForRequest(),
        ];

        return str_replace(array_keys($replacements), array_values($replacements), $url);
    }

    public function normalizedDevices(): array
    {
        $devices = $this->devices ?: ['android', 'ios', 'desktop'];

        return collect($devices)
            ->map(fn ($device) => strtolower((string) $device))
            ->flatMap(function ($device) {
                return match ($device) {
                    'all', 'web', 'any', 'all devices' => ['android', 'ios', 'desktop'],
                    'mobile' => ['android', 'ios'],
                    'iphone', 'ipad', 'ipod', 'apple' => ['ios'],
                    'pc', 'windows', 'mac', 'macos' => ['desktop'],
                    default => [$device],
                };
            })
            ->filter()
            ->unique()
            ->values()
            ->all();
    }
}
