<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CloudflareRecordSetting extends Model
{
    use HasFactory;

    protected $fillable = [
        'dns_record_id',
        'cloudflare_zone_id',
        'cloudflare_record_id',
        'proxied',
        'sync_enabled',
        'last_synced_at',
        'cloudflare_data',
    ];

    protected $casts = [
        'proxied' => 'boolean',
        'sync_enabled' => 'boolean',
        'last_synced_at' => 'datetime',
        'cloudflare_data' => 'array',
    ];

    /**
     * Relatie cu record-ul DNS local
     */
    public function dnsRecord()
    {
        return $this->belongsTo(DnsRecord::class, 'dns_record_id');
    }

    /**
     * Relatie cu zona Cloudflare
     */
    public function cloudflareZone()
    {
        return $this->belongsTo(CloudflareZone::class, 'cloudflare_zone_id');
    }

    /**
     * Scope pentru records cu proxy activ
     */
    public function scopeProxied($query)
    {
        return $query->where('proxied', true);
    }

    /**
     * Scope pentru records cu sync activ
     */
    public function scopeSyncEnabled($query)
    {
        return $query->where('sync_enabled', true);
    }

    /**
     * Toggle proxy status
     */
    public function toggleProxy(): bool
    {
        $this->proxied = !$this->proxied;
        $this->save();
        return $this->proxied;
    }

    /**
     * Marcheaza ca sincronizat
     */
    public function markSynced(?string $cloudflareRecordId = null, ?array $data = null): void
    {
        $update = ['last_synced_at' => now()];

        if ($cloudflareRecordId) {
            $update['cloudflare_record_id'] = $cloudflareRecordId;
        }

        if ($data) {
            $update['cloudflare_data'] = $data;
        }

        $this->update($update);
    }
}
