<?php

namespace Database\Factories;

use App\Models\Event;
use App\Models\Tenant;
use App\Models\TenantFeedback;
use Illuminate\Database\Eloquent\Factories\Factory;

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

    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'tenant_id' => Tenant::factory(),
            'event_id' => Event::factory(),
            'category' => $this->faker->randomElement(['bug', 'idea', 'praise', 'question']),
            'sentiment' => $this->faker->randomElement(['positive', 'neutral', 'negative']),
            'rating' => $this->faker->numberBetween(1, 5),
            'title' => $this->faker->sentence(4),
            'message' => $this->faker->paragraph(),
            'metadata' => ['source' => 'factory'],
            'status' => 'pending',
        ];
    }

    public function configure(): static
    {
        return $this->afterMaking(function (TenantFeedback $feedback) {
            if ($feedback->event && ! $feedback->tenant_id) {
                $feedback->tenant_id = $feedback->event->tenant_id;
            }
        })->afterCreating(function (TenantFeedback $feedback) {
            if ($feedback->event && ! $feedback->tenant_id) {
                $feedback->tenant_id = $feedback->event->tenant_id;
                $feedback->save();
            }

            if ($feedback->event && $feedback->tenant_id && $feedback->event->tenant_id !== $feedback->tenant_id) {
                $feedback->event->update(['tenant_id' => $feedback->tenant_id]);
            }
        });
    }
}
