<?php

declare(strict_types=1);

namespace Database\Seeders;

use App\Models\Producer;
use App\Models\Product;
use App\Models\Project;
use App\Models\Report;
use App\Models\ReportConsumable;
use App\Models\ReportFeedingMeal;
use App\Models\ReportInvoiceItem;
use App\Models\ReportItem;
use App\Models\ReportRationIngredient;
use App\Models\ReportRationWeekly;
use App\Models\User;
use Illuminate\Database\Seeder;

class TransparencyReportsDemoSeeder extends Seeder
{
    public function run(): void
    {
        $admin = User::role('admin')->first();
        $user = User::role('user')->first();
        $producer = Producer::first();
        $product = Product::first();
        $mainProject = Project::where('status', 'active')->orderBy('id')->first();
        $secondProject = Project::where('status', 'active')->orderByDesc('id')->first();

        if (! $admin || ! $mainProject || ! $product) {
            return;
        }

        $this->seedGrowthReports($admin, $user, $producer, $product, $mainProject);
        $this->seedHealthReports($admin, $user, $producer, $product, $mainProject);
        $this->seedRationReports($admin, $user, $producer, $mainProject);
        $this->seedLegacyReportsOnSecondProject($admin, $user, $producer, $product, $secondProject);
    }

    private function seedGrowthReports(User $admin, ?User $user, ?Producer $producer, Product $product, Project $project): void
    {
        $report = Report::updateOrCreate(
            [
                'project_id' => $project->id,
                'type' => Report::TYPE_GROWTH,
                'title' => 'گزارش وزن‌کشی ماهانه - بهمن ۱۴۰۴',
            ],
            [
                'user_id' => $user?->id ?? $admin->id,
                'producer_id' => $producer?->id,
                'product_id' => $product->id,
                'period' => 'ماهانه',
                'date' => now()->subDays(15)->toDateString(),
                'report_at' => now()->subDays(15),
                'report_type' => 'weight',
                'unit' => Report::UNIT_KG,
                'workflow_status' => Report::WORKFLOW_APPROVED,
                'status' => 'published',
                'metrics' => [
                    'current' => '۴۵۰ کیلوگرم',
                    'target' => '۵۲۰ کیلوگرم',
                    'percent' => 72,
                    'weight_gain' => 18,
                ],
                'written_report' => 'روند رشد گله در محدوده هدف قرار دارد. تغذیه و بهداشت مطلوب گزارش شد.',
                'created_by' => $admin->id,
                'updated_by' => $admin->id,
            ]
        );

        ReportItem::firstOrCreate(
            ['report_id' => $report->id, 'product_id' => $product->id],
            [
                'value' => 450,
                'min_value' => 420,
                'max_value' => 480,
                'unit' => 'kg',
                'sort_order' => 0,
            ]
        );
    }

    private function seedHealthReports(User $admin, ?User $user, ?Producer $producer, Product $product, Project $project): void
    {
        $treatment = Report::updateOrCreate(
            [
                'project_id' => $project->id,
                'type' => Report::TYPE_HEALTH,
                'title' => 'گزارش درمان mastitis - گاو کد ۰۳',
            ],
            [
                'user_id' => $user?->id ?? $admin->id,
                'producer_id' => $producer?->id,
                'product_id' => $product->id,
                'period' => 'درمان',
                'date' => now()->subDays(8)->toDateString(),
                'report_at' => now()->subDays(8),
                'report_type' => Report::HEALTH_TYPE_TREATMENT,
                'disease_name' => 'ورم پستان (Mastitis)',
                'diagnosis' => 'التهاب پستان خفیف، نیاز به آنتی‌بیوتیک و ماساژ.',
                'expert_opinion' => 'پیشنهاد ادامه درمان ۵ روز دیگر و پایش روزانه شیر.',
                'next_visit_at' => now()->addDays(5)->toDateString(),
                'total_cost' => 2_850_000,
                'workflow_status' => Report::WORKFLOW_APPROVED,
                'status' => 'published',
                'written_report' => 'درمان با موفقیت آغاز شد. دام تحت نظر است.',
                'attachments' => [
                    'files/gav-2.jpg',
                ],
                'created_by' => $admin->id,
                'updated_by' => $admin->id,
            ]
        );

        ReportItem::firstOrCreate(
            ['report_id' => $treatment->id, 'product_id' => $product->id],
            ['sort_order' => 0]
        );

        $consumables = [
            ['name' => 'آنتی‌بیوتیک پنی‌سیلین', 'unit' => 'عدد', 'quantity' => 5],
            ['name' => 'پماد ضدالتهاب', 'unit' => 'عدد', 'quantity' => 2],
            ['name' => 'سرم ویتامینه', 'unit' => 'لیتر', 'quantity' => 1.5],
        ];

        foreach ($consumables as $i => $row) {
            ReportConsumable::firstOrCreate(
                ['report_id' => $treatment->id, 'name' => $row['name']],
                array_merge($row, ['sort_order' => $i])
            );
        }

        $invoiceLines = [
            ['title' => 'حق‌الزحمه دامپزشک', 'amount' => 1_500_000],
            ['title' => 'دارو و لوازم', 'amount' => 1_050_000],
            ['title' => 'حمل و نقل', 'amount' => 300_000],
        ];

        foreach ($invoiceLines as $i => $line) {
            ReportInvoiceItem::firstOrCreate(
                ['report_id' => $treatment->id, 'title' => $line['title']],
                ['amount' => $line['amount'], 'sort_order' => $i]
            );
        }

        Report::updateOrCreate(
            [
                'project_id' => $project->id,
                'type' => Report::TYPE_HEALTH,
                'title' => 'واکسیناسیون دوره‌ای گله',
            ],
            [
                'user_id' => $user?->id ?? $admin->id,
                'producer_id' => $producer?->id,
                'date' => now()->subDays(21)->toDateString(),
                'report_at' => now()->subDays(21),
                'report_type' => Report::HEALTH_TYPE_OTHER,
                'disease_name' => 'پیشگیری',
                'diagnosis' => 'واکسیناسیون برنامه‌ای انجام شد.',
                'total_cost' => 1_200_000,
                'workflow_status' => Report::WORKFLOW_APPROVED,
                'status' => 'published',
                'created_by' => $admin->id,
                'updated_by' => $admin->id,
            ]
        );
    }

    private function seedRationReports(User $admin, ?User $user, ?Producer $producer, Project $project): void
    {
        $report = Report::updateOrCreate(
            [
                'project_id' => $project->id,
                'type' => Report::TYPE_RATION,
                'title' => 'جیره شیری بهمن ۱۴۰۴',
            ],
            [
                'user_id' => $user?->id ?? $admin->id,
                'producer_id' => $producer?->id,
                'date' => now()->subDays(5)->toDateString(),
                'report_at' => now()->subDays(5),
                'ration_type' => 'TMR',
                'mix_type' => Report::MIX_MACHINE,
                'water_temp' => 22,
                'water_per_unit_daily' => 85,
                'wait_between_meals_hours' => 6,
                'warnings' => 'از افزایش ناگهانی کنسانتره خودداری شود.',
                'workflow_status' => Report::WORKFLOW_APPROVED,
                'status' => 'published',
                'written_report' => 'جیره TMR با نسبت‌های تایید شده تولیدکننده تنظیم شد.',
                'created_by' => $admin->id,
                'updated_by' => $admin->id,
            ]
        );

        $ingredients = [
            ['name' => 'یونجه', 'unit' => 'kg', 'quantity_per_unit' => 12, 'price_per_unit' => 3_000],
            ['name' => 'کنسانتره شیری', 'unit' => 'kg', 'quantity_per_unit' => 8, 'price_per_unit' => 45_000],
            ['name' => 'سبوس گندم', 'unit' => 'kg', 'quantity_per_unit' => 3, 'price_per_unit' => 8_000],
        ];

        foreach ($ingredients as $i => $ing) {
            ReportRationIngredient::firstOrCreate(
                ['report_id' => $report->id, 'name' => $ing['name']],
                array_merge($ing, ['sort_order' => $i])
            );
        }

        $meals = [
            ['meal_time' => '06:30', 'name' => 'صبح', 'percent_of_total' => 40],
            ['meal_time' => '14:00', 'name' => 'ظهر', 'percent_of_total' => 30],
            ['meal_time' => '20:00', 'name' => 'شب', 'percent_of_total' => 30],
        ];

        foreach ($meals as $i => $meal) {
            ReportFeedingMeal::firstOrCreate(
                ['report_id' => $report->id, 'meal_time' => $meal['meal_time']],
                array_merge($meal, ['sort_order' => $i])
            );
        }

        for ($day = 1; $day <= 7; $day++) {
            ReportRationWeekly::firstOrCreate(
                ['report_id' => $report->id, 'day_of_week' => $day],
                [
                    'is_active' => true,
                    'status' => $day === 7 ? ReportRationWeekly::STATUS_FAST : ReportRationWeekly::STATUS_NORMAL,
                ]
            );
        }
    }

    private function seedLegacyReportsOnSecondProject(
        User $admin,
        ?User $user,
        ?Producer $producer,
        Product $product,
        ?Project $project
    ): void {
        if (! $project) {
            return;
        }

        Report::updateOrCreate(
            [
                'project_id' => $project->id,
                'type' => Report::TYPE_GROWTH,
                'title' => 'گزارش رشد گله گوسفند',
            ],
            [
                'user_id' => $user?->id ?? $admin->id,
                'producer_id' => $producer?->id,
                'product_id' => $product->id,
                'date' => now()->subDays(10)->toDateString(),
                'report_at' => now()->subDays(10),
                'workflow_status' => Report::WORKFLOW_APPROVED,
                'status' => 'published',
                'metrics' => ['current' => '۳۸ کیلوگرم', 'target' => '۴۵ کیلوگرم', 'percent' => 65],
                'created_by' => $admin->id,
                'updated_by' => $admin->id,
            ]
        );
    }
}
