<?php

namespace App\Master\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Stancl\Tenancy\Database\Concerns\CentralConnection;

class AutoTraderAdvertiser extends Model
{
    use CentralConnection;

    protected $table = 'autotrader_advertisers';

    protected $fillable = [
        'advertiser_id',
        'name',
        'description',
        'status',
        'segment',
        'phone',
        'website',
        'location',
        'new_vehicle_strapline',
        'used_vehicle_strapline',
        'autotrader_advert_allowances',
        'capabilities',
        'last_fetched_at',
    ];

    protected $casts = [
        'location' => 'array',
        'autotrader_advert_allowances' => 'array',
        'capabilities' => 'array',
        'last_fetched_at' => 'datetime',
    ];

    /**
     * Upsert an advertiser from the API response data (camelCase keys).
     */
    public static function upsertFromApiResponse(array $data): self
    {
        return self::updateOrCreate(
            ['advertiser_id' => $data['advertiserId']],
            [
                'name' => $data['name'] ?? null,
                'description' => $data['description'] ?? null,
                'status' => $data['status'] ?? null,
                'segment' => $data['segment'] ?? null,
                'phone' => $data['phone'] ?? null,
                'website' => $data['website'] ?? null,
                'location' => $data['location'] ?? null,
                'new_vehicle_strapline' => $data['newVehicleStrapline'] ?? null,
                'used_vehicle_strapline' => $data['usedVehicleStrapline'] ?? null,
                'autotrader_advert_allowances' => $data['autotraderAdvertAllowances'] ?? null,
                'capabilities' => $data['capabilities'] ?? null,
                'last_fetched_at' => Carbon::now(),
            ]
        );
    }

    /**
     * Convert to camelCase format matching the API response shape.
     */
    public function toApiFormat(): array
    {
        return [
            'advertiserId' => $this->advertiser_id,
            'name' => $this->name,
            'description' => $this->description,
            'status' => $this->status,
            'segment' => $this->segment,
            'phone' => $this->phone,
            'website' => $this->website,
            'location' => $this->location,
            'newVehicleStrapline' => $this->new_vehicle_strapline,
            'usedVehicleStrapline' => $this->used_vehicle_strapline,
            'autotraderAdvertAllowances' => $this->autotrader_advert_allowances,
            'capabilities' => $this->capabilities,
            'lastFetchedAt' => $this->last_fetched_at?->toIso8601String(),
        ];
    }
}
