<?php

declare(strict_types=1);

namespace Database\Seeders;

use App\Models\AdminMessage;
use App\Models\AdminMessageRecipient;
use App\Models\ConsultationRequest;
use App\Models\Discussion;
use App\Models\DiscussionMessage;
use App\Models\DiscussionParticipant;
use App\Models\SupportTicket;
use App\Models\SupportTicketReply;
use Database\Seeders\Support\DemoSeederContext;
use Illuminate\Database\Seeder;

class DemoCommunicationsSeeder extends Seeder
{
    public function run(): void
    {
        $admin = DemoSeederContext::admin();
        $employer = DemoSeederContext::employer();
        $producer = DemoSeederContext::producer();
        $expert = DemoSeederContext::expert();
        $project = DemoSeederContext::mainProject();

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

        $this->seedDiscussions($admin, $employer, $project);
        $this->seedSupportTickets($admin, $employer);
        $this->seedConsultations($admin, $producer, $expert);
        $this->seedAdminMessages($admin, $employer, $project);
    }

    private function seedDiscussions($admin, $employer, $project): void
    {
        $producerUser = DemoSeederContext::producerUser();

        $active = Discussion::firstOrCreate(
            [
                'project_id' => $project->id,
                'title' => 'گفتگوی پیشرفت پروژه',
            ],
            [
                'hashtag' => 'progress',
                'initial_message' => 'سلام، وضعیت هفته جاری پروژه چگونه است؟',
                'status' => Discussion::STATUS_ACTIVE,
                'created_by' => $employer->id,
            ]
        );

        $ended = Discussion::firstOrCreate(
            [
                'project_id' => $project->id,
                'title' => 'گفتگوی بایگانی‌شده',
            ],
            [
                'initial_message' => 'این گفتگو پایان یافته است.',
                'status' => Discussion::STATUS_ENDED,
                'created_by' => $admin->id,
            ]
        );

        foreach ([$active, $ended] as $discussion) {
            foreach (Discussion::projectUserIds($project) as $userId) {
                DiscussionParticipant::firstOrCreate([
                    'discussion_id' => $discussion->id,
                    'user_id' => $userId,
                ]);
            }
        }

        $messages = [
            [$active->id, $employer->id, 'لطفاً گزارش وزن‌کشی را ارسال کنید.'],
            [$active->id, $producerUser?->id ?? $admin->id, 'گزارش هفته جاری آپلود شد.'],
            [$active->id, $admin->id, 'ممنون، در پنل بررسی می‌شود.'],
            [$ended->id, $employer->id, 'این موضوع بسته شد.'],
        ];

        foreach ($messages as [$discussionId, $userId, $body]) {
            if (! $userId) {
                continue;
            }

            DiscussionMessage::firstOrCreate(
                [
                    'discussion_id' => $discussionId,
                    'user_id' => $userId,
                    'body' => $body,
                ],
                ['created_at' => now()->subDays(rand(1, 10))]
            );
        }
    }

    private function seedSupportTickets($admin, $employer): void
    {
        $open = SupportTicket::firstOrCreate(
            ['code' => 'TDEMOOPEN1'],
            [
                'user_id' => $employer->id,
                'category' => SupportTicket::CATEGORY_FINANCIAL,
                'title' => 'سوال درباره برداشت کیف پول',
                'body' => 'زمان واریز درخواست برداشت چقدر طول می‌کشد؟',
                'status' => SupportTicket::STATUS_UNREAD,
                'created_by' => $employer->id,
            ]
        );

        $closed = SupportTicket::firstOrCreate(
            ['code' => 'TDEMOCLOSE1'],
            [
                'user_id' => $employer->id,
                'category' => SupportTicket::CATEGORY_PROJECT,
                'title' => 'درخواست گزارش پروژه',
                'body' => 'لطفاً گزارش ماه گذشته را ارسال کنید.',
                'status' => SupportTicket::STATUS_CLOSED,
                'closed_at' => now()->subDays(3),
                'closed_by' => $admin->id,
                'close_reason' => 'پاسخ داده شد',
                'created_by' => $employer->id,
            ]
        );

        SupportTicketReply::firstOrCreate(
            [
                'support_ticket_id' => $open->id,
                'user_id' => $admin->id,
                'body' => 'درخواست‌های تایید‌شده معمولاً تا ۴۸ ساعت واریز می‌شوند.',
            ],
            ['is_admin' => true]
        );

        SupportTicketReply::firstOrCreate(
            [
                'support_ticket_id' => $closed->id,
                'user_id' => $admin->id,
                'body' => 'گزارش از بخش شفافیت پروژه قابل مشاهده است.',
            ],
            ['is_admin' => true]
        );
    }

    private function seedConsultations($admin, $producer, $expert): void
    {
        if (! $producer || ! $expert) {
            return;
        }

        ConsultationRequest::firstOrCreate(
            [
                'producer_id' => $producer->id,
                'expert_id' => $expert->id,
                'status' => ConsultationRequest::STATUS_PENDING,
            ],
            [
                'type' => ConsultationRequest::TYPE_FEED,
                'format' => ConsultationRequest::FORMAT_ONLINE,
                'priority' => ConsultationRequest::PRIORITY_NORMAL,
                'message' => 'نیاز به بررسی جیره گله داریم.',
            ]
        );

        ConsultationRequest::firstOrCreate(
            [
                'producer_id' => $producer->id,
                'expert_id' => $expert->id,
                'status' => ConsultationRequest::STATUS_APPROVED,
            ],
            [
                'type' => ConsultationRequest::TYPE_HERD,
                'format' => ConsultationRequest::FORMAT_IN_PERSON,
                'priority' => ConsultationRequest::PRIORITY_URGENT,
                'message' => 'معاینه حضوری گله',
                'production_address' => 'البرز، کرج، واحد گاوداری',
                'producer_contact' => '09122222222',
                'provider_can_visit' => true,
            ]
        );

        ConsultationRequest::firstOrCreate(
            [
                'producer_id' => $producer->id,
                'expert_id' => $expert->id,
                'status' => ConsultationRequest::STATUS_REJECTED,
            ],
            [
                'type' => ConsultationRequest::TYPE_OTHER,
                'format' => ConsultationRequest::FORMAT_ONLINE,
                'priority' => ConsultationRequest::PRIORITY_LOW,
                'message' => 'درخواست رد شده نمونه',
                'admin_notes' => 'اطلاعات ناقص بود.',
            ]
        );

        ConsultationRequest::firstOrCreate(
            [
                'producer_id' => $producer->id,
                'expert_id' => $expert->id,
                'status' => ConsultationRequest::STATUS_CLOSED,
            ],
            [
                'type' => ConsultationRequest::TYPE_FEED,
                'format' => ConsultationRequest::FORMAT_IN_PERSON,
                'priority' => ConsultationRequest::PRIORITY_NORMAL,
                'message' => 'مشاوره انجام و بسته شد.',
                'closed_at' => now()->subWeek(),
                'closed_by' => $admin->id,
            ]
        );
    }

    private function seedAdminMessages($admin, $employer, $project): void
    {
        $draft = AdminMessage::firstOrCreate(
            ['title' => 'پیام پیش‌نویس دمو'],
            [
                'body' => 'این پیام هنوز ارسال نشده است.',
                'status' => AdminMessage::STATUS_DRAFT,
                'channel' => AdminMessage::CHANNEL_INTERNAL,
                'project_id' => $project->id,
                'created_by' => $admin->id,
            ]
        );

        $sent = AdminMessage::firstOrCreate(
            ['title' => 'اطلاع‌رسانی به سرمایه‌گذاران'],
            [
                'body' => 'گزارش ماهانه پروژه منتشر شد.',
                'status' => AdminMessage::STATUS_SENT,
                'channel' => AdminMessage::CHANNEL_SMS,
                'project_id' => $project->id,
                'sent_at' => now()->subDays(2),
                'recipient_filters' => ['account_type' => 'employer'],
                'created_by' => $admin->id,
            ]
        );

        AdminMessageRecipient::firstOrCreate(
            [
                'admin_message_id' => $sent->id,
                'user_id' => $employer->id,
            ],
            [
                'channel' => AdminMessage::CHANNEL_SMS,
                'status' => 'sent',
            ]
        );

        unset($draft);
    }
}
