<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class EmailMessage extends Model
{
    protected $fillable = [
        'subject',
        'content_html',
        'status',
        'schedule_at',
        'sent_at',
        'created_by'
    ];

    protected $casts = [
        'schedule_at' => 'datetime',
        'sent_at' => 'datetime',
    ];

    public function recipients()
    {
        return $this->hasMany(EmailMessageRecipient::class);
    }
    public function attachments()
    {
        return $this->hasMany(EmailMessageAttachment::class);
    }
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function duplicate(bool $withRecipients = false)
    {
        return DB::transaction(function () use ($withRecipients) {
            $copy = $this->replicate(['status', 'schedule_at', 'sent_at']);
            $copy->status = 'draft';
            $copy->schedule_at = null;
            $copy->sent_at = null;
            $copy->save();

            foreach ($this->attachments as $a) {
                $copy->attachments()->create($a->only(['disk', 'path', 'name', 'size']));
            }

            if ($withRecipients) {
                $payload = $this->recipients()
                    ->get(['member_id', 'email_address'])
                    ->map(fn($r) => [
                        'member_id' => $r->member_id,
                        'email_address' => $r->email_address,
                        'status' => 'pending',
                    ])
                    ->all();

                if ($payload) {
                    $copy->recipients()->createMany($payload);
                }
            }

            return $copy;
        });
    }

    public function isLocked(): bool
    {
        return in_array($this->status, ['processing', 'sent']);
    }
}
