<?php

declare(strict_types=1);

namespace Database\Seeders;

use App\Models\Offer;
use App\Models\Order;
use App\Models\Producer;
use App\Models\Product;
use App\Models\Project;
use App\Models\ProjectContractSignature;
use App\Models\ProjectRequest;
use Database\Seeders\Support\DemoSeederContext;
use Illuminate\Database\Seeder;
use Mortezaa97\Regions\Models\County;
use Mortezaa97\Regions\Models\Province;

class DemoWorkflowSeeder extends Seeder
{
    public function run(): void
    {
        $admin = DemoSeederContext::admin();
        $employer = DemoSeederContext::employer();
        $producer = DemoSeederContext::producer();
        $product = Product::query()->first();
        $category = \App\Models\Category::query()->where('slug', 'cattle')->first();
        $breed = \App\Models\Breed::query()->first();
        $province = Province::query()->first();
        $county = County::query()->where('province_id', $province?->id)->first();

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

        $this->seedExtraProjects($admin, $employer, $producer, $product, $category, $breed, $province, $county);
        $this->seedOrders($admin, $employer, $producer, $product, $province, $county);
        $this->seedOffers($admin, $employer, $producer, $product);
        $this->seedProjectRequests($admin, $producer);
        $this->seedContractSignatures($employer, $producer);
    }

    private function seedExtraProjects(
        $admin,
        $employer,
        Producer $producer,
        Product $product,
        $category,
        $breed,
        ?Province $province,
        ?County $county,
    ): void {
        $projects = [
            [
                'name' => 'پروژه گاوداری در انتظار امضا',
                'status' => Project::STATUS_UNSIGNED,
                'excerpt' => 'قرارداد امضا نشده — نمایش فرآیند امضا',
                'budget' => 55_000_000,
            ],
            [
                'name' => 'پروژه پرواربندی در انتظار تایید',
                'status' => Project::STATUS_WAITING,
                'excerpt' => 'در صف بررسی ادمین',
                'budget' => 38_000_000,
            ],
            [
                'name' => 'پروژه لغوشده نمونه',
                'status' => Project::STATUS_CANCELLED,
                'excerpt' => 'نمونه پروژه لغوشده',
                'budget' => 20_000_000,
            ],
        ];

        foreach ($projects as $data) {
            Project::updateOrCreate(
                ['name' => $data['name']],
                [
                    'user_id' => $employer->id,
                    'producer_id' => $producer->id,
                    'category_id' => $category?->id,
                    'product_id' => $product->id,
                    'breed_id' => $breed?->id,
                    'excerpt' => $data['excerpt'],
                    'desc' => $data['excerpt'],
                    'budget' => $data['budget'],
                    'estimated_profit' => (int) ($data['budget'] * 0.15),
                    'status' => $data['status'],
                    'quantity' => 20,
                    'unit' => Project::UNIT_HEAD,
                    'start_date' => now()->subMonth(),
                    'end_date' => now()->addMonths(6),
                    'images' => ['files/gav.jpg'],
                    'contract_text' => 'متن قرارداد نمونه برای ' . $data['name'],
                    'province_id' => $province?->id,
                    'county_id' => $county?->id,
                    'address' => 'البرز، کرج',
                    'created_by' => $admin->id,
                    'updated_by' => $admin->id,
                ]
            );
        }
    }

    private function seedOrders($admin, $employer, Producer $producer, Product $product, ?Province $province, ?County $county): void
    {
        $mainProject = DemoSeederContext::mainProject();

        $orders = [
            [
                'order_number' => 'ORD-DEMO-CONFIRMED',
                'status' => 'confirmed',
                'project_id' => $mainProject?->id,
                'quantity' => 2,
            ],
            [
                'order_number' => 'ORD-DEMO-DELIVERED',
                'status' => 'delivered',
                'project_id' => $mainProject?->id,
                'quantity' => 1,
            ],
            [
                'order_number' => 'ORD-DEMO-CANCELLED',
                'status' => 'cancelled',
                'project_id' => null,
                'quantity' => 1,
            ],
        ];

        foreach ($orders as $row) {
            Order::firstOrCreate(
                ['order_number' => $row['order_number']],
                [
                    'user_id' => $employer->id,
                    'producer_id' => $producer->id,
                    'product_id' => $product->id,
                    'project_id' => $row['project_id'],
                    'type' => 'order',
                    'quantity' => $row['quantity'],
                    'unit' => 'راس',
                    'unit_price' => $product->price,
                    'total_price' => (int) $product->price * $row['quantity'],
                    'order_date' => now()->subDays(rand(3, 20)),
                    'status' => $row['status'],
                    'province_id' => $province?->id,
                    'county_id' => $county?->id,
                    'delivery_address' => 'آدرس تحویل دمو',
                    'created_by' => $admin->id,
                    'updated_by' => $admin->id,
                ]
            );
        }
    }

    private function seedOffers($admin, $employer, Producer $producer, Product $product): void
    {
        $project = DemoSeederContext::mainProject();
        $producerUser = DemoSeederContext::producerUser();

        Offer::firstOrCreate(
            ['name' => 'پیشنهاد پذیرفته‌شده دمو'],
            [
                'user_id' => $producerUser?->id ?? $employer->id,
                'product_id' => $product->id,
                'project_id' => $project?->id,
                'description' => 'پیشنهاد تایید شده برای نمایش وضعیت accepted',
                'price' => 130_000_000,
                'quantity' => 1,
                'unit' => 'راس',
                'offer_date' => now()->subDays(10),
                'status' => Offer::STATUS_ACCEPTED,
                'created_by' => $admin->id,
                'updated_by' => $admin->id,
            ]
        );

        Offer::firstOrCreate(
            ['name' => 'پیشنهاد رد شده دمو'],
            [
                'user_id' => $employer->id,
                'product_id' => $product->id,
                'description' => 'پیشنهاد رد شده',
                'price' => 90_000_000,
                'quantity' => 1,
                'unit' => 'راس',
                'offer_date' => now()->subDays(5),
                'status' => Offer::STATUS_REJECTED,
                'created_by' => $admin->id,
                'updated_by' => $admin->id,
            ]
        );

        Offer::firstOrCreate(
            ['name' => 'پیشنهاد منقضی دمو'],
            [
                'user_id' => $employer->id,
                'project_id' => $project?->id,
                'description' => 'پیشنهاد منقضی شده',
                'price' => 40_000_000,
                'offer_date' => now()->subMonths(2),
                'expiry_date' => now()->subMonth(),
                'status' => Offer::STATUS_EXPIRED,
                'created_by' => $admin->id,
                'updated_by' => $admin->id,
            ]
        );
    }

    private function seedProjectRequests($admin, Producer $producer): void
    {
        ProjectRequest::firstOrCreate(
            [
                'producer_id' => $producer->id,
                'title' => 'درخواست ایجاد پروژه جدید',
                'status' => ProjectRequest::STATUS_WAITING,
            ],
            [
                'payload' => [
                    'budget' => 60_000_000,
                    'quantity' => 30,
                ],
                'created_by' => $producer->user_id,
            ]
        );

        $approvedProject = DemoSeederContext::mainProject();
        if ($approvedProject) {
            ProjectRequest::firstOrCreate(
                [
                    'producer_id' => $producer->id,
                    'project_id' => $approvedProject->id,
                    'title' => 'درخواست تایید ' . $approvedProject->name,
                    'status' => ProjectRequest::STATUS_APPROVED,
                ],
                [
                    'payload' => ['name' => $approvedProject->name],
                    'reviewed_by' => $admin->id,
                    'reviewed_at' => now()->subMonths(4),
                    'created_by' => $producer->user_id,
                ]
            );
        }
    }

    private function seedContractSignatures($employer, Producer $producer): void
    {
        $unsignedProject = Project::query()
            ->where('status', Project::STATUS_UNSIGNED)
            ->first();

        if (! $unsignedProject) {
            return;
        }

        ProjectContractSignature::firstOrCreate(
            [
                'project_id' => $unsignedProject->id,
                'user_id' => $employer->id,
                'role' => ProjectContractSignature::ROLE_EMPLOYER,
            ],
            ['signed_at' => now()->subDays(2)]
        );

        ProjectContractSignature::firstOrCreate(
            [
                'project_id' => $unsignedProject->id,
                'user_id' => $producer->user_id,
                'role' => ProjectContractSignature::ROLE_PRODUCER,
            ]
        );
    }
}
