<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Validator;

class RemoteEmail extends Model
{
    use HasFactory;

    protected $table = 'emails';

    public function getConnectionName()
    {
        if (app()->environment('testing')) {
            return config('database.default');
        }

        return 'mysql_remote';
    }

    protected $fillable = [
        'message_id',
        'subject',
        'from_name',
        'from_email',
        'to',
        'body_html',
        'body_text',
        'is_seen',
        'timestamp',
    ];

    protected $casts = [
        'to' => 'array',
        'is_seen' => 'boolean',
        'timestamp' => 'datetime',
    ];

    public static function fetchEmailFromDB($email)
    {
        $validator = Validator::make(['email' => $email], [
            'email' => ['required', 'email'],
        ]);

        if ($validator->fails()) {
            return [];
        }

        return self::query()->whereJsonContains('to', $email)->orderBy('timestamp', 'desc')->get();
    }
}
