<?php

namespace Database\Factories;

use App\Enums\FolderPriority;
use App\Enums\FolderStatus;
use App\Enums\FolderType;
use App\Models\Client;
use App\Models\Workspace;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Folder>
 */
class FolderFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        $workspace = Workspace::factory()->create();
        $client = Client::factory()->create(['workspace_id' => $workspace->id]);

        $year = fake()->numberBetween(2024, 2026);
        $excludeOldVat = array_filter(FolderType::getValues(), fn ($v) => $v !== 'vat');
        $type = fake()->randomElement(array_values($excludeOldVat));

        $isVatMonthly = $type === 'vat_monthly';
        $isVatQuarterly = $type === 'vat_quarterly';

        return [
            'workspace_id' => $workspace->id,
            'client_id' => $client->id,
            'created_by' => null,
            'title' => 'Déclaration '.$this->typeLabel($type).' - '.$year,
            'type' => $type,
            'period_year' => $year,
            'period_month' => $isVatMonthly ? fake()->numberBetween(1, 12) : null,
            'period_quarter' => $isVatQuarterly ? fake()->numberBetween(1, 4) : null,
            'due_date' => fake()->dateTimeBetween('now', '+3 months'),
            'status' => fake()->randomElement(FolderStatus::getValues()),
            'priority' => fake()->randomElement(FolderPriority::getValues()),
            'assigned_to' => null,
            'validated_at' => null,
            'closed_at' => null,
            'notes_internal' => fake()->optional(0.3)->sentence(),
            'notes_client' => null,
        ];
    }

    /**
     * Configure the model factory to use existing workspace and client.
     */
    public function forWorkspace(Workspace $workspace): static
    {
        return $this->state(fn () => [
            'workspace_id' => $workspace->id,
            'client_id' => Client::factory()->create(['workspace_id' => $workspace->id])->id,
        ]);
    }

    private function typeLabel(string $type): string
    {
        return match ($type) {
            'vat' => 'TVA',
            'vat_monthly' => 'TVA mensuelle',
            'vat_quarterly' => 'TVA trimestrielle',
            'corporate_tax' => 'IS',
            'income_tax' => 'IR',
            'cnss' => 'CNSS',
            'annual_balance' => 'Bilan',
            default => 'Autre',
        };
    }
}
