<?php

namespace Database\Factories;

use App\Models\Email;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Email>
 */
class EmailFactory extends Factory
{
    protected $model = Email::class;

    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        $domain = fake()->domainName();
        $bodyText = fake()->paragraphs(3, true);

        return [
            'unique_id_hash' => hash('sha256', fake()->uuid()),
            'recipient_email' => fake()->userName().'@'.$domain,
            'recipient_name' => fake()->name(),
            'sender_email' => fake()->safeEmail(),
            'sender_name' => fake()->name(),
            'domain' => $domain,
            'subject' => fake()->sentence(6),
            'preview' => mb_substr($bodyText, 0, 500),
            'attachments_json' => [],
            'attachment_size' => 0,
            'is_read' => false,
            'received_at' => fake()->dateTimeBetween('-7 days', 'now'),
        ];
    }

    /**
     * Mark the email as read.
     */
    public function read(): static
    {
        return $this->state(fn (array $attributes) => [
            'is_read' => true,
        ]);
    }

    /**
     * Add attachments to the email.
     */
    public function withAttachments(int $count = 1): static
    {
        return $this->state(function (array $attributes) use ($count) {
            $attachments = [];
            $totalSize = 0;

            for ($i = 0; $i < $count; $i++) {
                $size = fake()->numberBetween(1024, 5242880);
                $totalSize += $size;
                $attachments[] = [
                    'filename' => fake()->word().'.'.fake()->fileExtension(),
                    'mimeType' => fake()->mimeType(),
                    'size' => $size,
                    's3_path' => 'mail-attachments/'.now()->format('Y/m/d').'/'.fake()->sha256().'_'.fake()->word().'.pdf',
                ];
            }

            return [
                'attachments_json' => $attachments,
                'attachment_size' => $totalSize,
            ];
        });
    }
}
