<?php
declare(strict_types=1);

use App\Core\Database;

return function (Database $db): void {
    $ts = date('Y-m-d H:i:s');

    $definitions = [
        [
            'workflow_code' => 'new_membership',
            'name_ar'       => 'عضوية جديدة',
            'name_en'       => 'New Membership',
            'description_ar' => 'دورة عمل تسجيل عضوية جديدة من تقديم الاستمارة حتى التفعيل',
            'definition_json' => json_encode([
                'states' => [
                    'form_submitted'       => ['label_ar' => 'تم تقديم الاستمارة',      'label_en' => 'Form Submitted',        'type' => 'initial'],
                    'under_review'         => ['label_ar' => 'تحت المراجعة',            'label_en' => 'Under Review',          'type' => 'intermediate'],
                    'interview_scheduled'  => ['label_ar' => 'تم تحديد موعد المقابلة',  'label_en' => 'Interview Scheduled',   'type' => 'intermediate'],
                    'accepted'             => ['label_ar' => 'مقبول',                    'label_en' => 'Accepted',              'type' => 'intermediate'],
                    'rejected'             => ['label_ar' => 'مرفوض',                    'label_en' => 'Rejected',              'type' => 'terminal'],
                    'payment_pending'      => ['label_ar' => 'في انتظار السداد',        'label_en' => 'Payment Pending',       'type' => 'intermediate'],
                    'active'               => ['label_ar' => 'فعال',                     'label_en' => 'Active',                'type' => 'terminal'],
                    'expired'              => ['label_ar' => 'منتهي الصلاحية',          'label_en' => 'Expired',               'type' => 'terminal'],
                ],
                'transitions' => [
                    [
                        'name' => 'start_review',
                        'from' => 'form_submitted',
                        'to'   => 'under_review',
                        'guards' => [['type' => 'permission', 'value' => 'member.edit']],
                        'actions' => [],
                    ],
                    [
                        'name' => 'schedule_interview',
                        'from' => 'under_review',
                        'to'   => 'interview_scheduled',
                        'guards' => [['type' => 'permission', 'value' => 'interview.schedule']],
                        'actions' => [['type' => 'event', 'value' => 'interview.scheduled']],
                    ],
                    [
                        'name' => 'accept',
                        'from' => 'interview_scheduled',
                        'to'   => 'payment_pending',
                        'guards' => [['type' => 'permission', 'value' => 'interview.decide']],
                        'actions' => [['type' => 'event', 'value' => 'member.accepted']],
                    ],
                    [
                        'name' => 'reject',
                        'from' => 'interview_scheduled',
                        'to'   => 'rejected',
                        'guards' => [['type' => 'permission', 'value' => 'interview.decide']],
                        'actions' => [['type' => 'event', 'value' => 'member.rejected']],
                    ],
                    [
                        'name' => 'reject_from_review',
                        'from' => 'under_review',
                        'to'   => 'rejected',
                        'guards' => [['type' => 'permission', 'value' => 'interview.decide']],
                        'actions' => [['type' => 'event', 'value' => 'member.rejected']],
                    ],
                    [
                        'name' => 'payment_completed',
                        'from' => 'payment_pending',
                        'to'   => 'active',
                        'guards' => [['type' => 'condition', 'value' => 'has_payment_receipt']],
                        'actions' => [['type' => 'event', 'value' => 'member.activated']],
                    ],
                    [
                        'name' => 'expire',
                        'from' => 'payment_pending',
                        'to'   => 'expired',
                        'guards' => [['type' => 'timeout', 'days' => 15]],
                        'trigger' => 'automatic',
                        'actions' => [['type' => 'event', 'value' => 'member.form_expired']],
                    ],
                ],
            ], JSON_UNESCAPED_UNICODE),
        ],
        [
            'workflow_code' => 'addition',
            'name_ar'       => 'إضافة (زوج/أبناء/مؤقت)',
            'name_en'       => 'Addition (Spouse/Children/Temporary)',
            'description_ar' => 'دورة عمل إضافة أفراد للعضوية',
            'definition_json' => json_encode([
                'states' => [
                    'addition_requested' => ['label_ar' => 'طلب إضافة مقدّم',     'label_en' => 'Addition Requested',  'type' => 'initial'],
                    'under_review'       => ['label_ar' => 'تحت المراجعة',        'label_en' => 'Under Review',        'type' => 'intermediate'],
                    'approved'           => ['label_ar' => 'موافق عليه',          'label_en' => 'Approved',            'type' => 'intermediate'],
                    'rejected'           => ['label_ar' => 'مرفوض',               'label_en' => 'Rejected',            'type' => 'terminal'],
                    'fee_pending'        => ['label_ar' => 'في انتظار الرسوم',    'label_en' => 'Fee Pending',         'type' => 'intermediate'],
                    'fee_paid'           => ['label_ar' => 'تم سداد الرسوم',      'label_en' => 'Fee Paid',            'type' => 'intermediate'],
                    'active'             => ['label_ar' => 'فعال',                'label_en' => 'Active',              'type' => 'terminal'],
                ],
                'transitions' => [
                    ['name' => 'start_review',    'from' => 'addition_requested', 'to' => 'under_review', 'guards' => [['type' => 'permission', 'value' => 'member.edit']], 'actions' => []],
                    ['name' => 'approve',         'from' => 'under_review',       'to' => 'fee_pending',  'guards' => [['type' => 'permission', 'value' => 'member.edit']], 'actions' => [['type' => 'event', 'value' => 'addition.approved']]],
                    ['name' => 'reject',          'from' => 'under_review',       'to' => 'rejected',     'guards' => [['type' => 'permission', 'value' => 'member.edit']], 'actions' => [['type' => 'event', 'value' => 'addition.rejected']]],
                    ['name' => 'record_payment',  'from' => 'fee_pending',        'to' => 'active',       'guards' => [['type' => 'condition', 'value' => 'has_payment_receipt']], 'actions' => [['type' => 'event', 'value' => 'addition.activated']]],
                ],
            ], JSON_UNESCAPED_UNICODE),
        ],
        [
            'workflow_code' => 'annual_subscription',
            'name_ar'       => 'الاشتراك السنوي',
            'name_en'       => 'Annual Subscription',
            'description_ar' => 'دورة عمل تجديد الاشتراك السنوي وتتبع التأخير',
            'definition_json' => json_encode([
                'states' => [
                    'renewal_due'        => ['label_ar' => 'مستحق التجديد',       'label_en' => 'Renewal Due',         'type' => 'initial'],
                    'notification_sent'  => ['label_ar' => 'تم إرسال الإخطار',    'label_en' => 'Notification Sent',   'type' => 'intermediate'],
                    'paid'               => ['label_ar' => 'مدفوع',               'label_en' => 'Paid',                'type' => 'terminal'],
                    'overdue'            => ['label_ar' => 'متأخر',               'label_en' => 'Overdue',             'type' => 'intermediate'],
                    'fine_applied'       => ['label_ar' => 'تم تطبيق الغرامة',    'label_en' => 'Fine Applied',        'type' => 'intermediate'],
                    'paid_with_fine'     => ['label_ar' => 'مدفوع مع غرامة',      'label_en' => 'Paid With Fine',      'type' => 'terminal'],
                    'membership_dropped' => ['label_ar' => 'تم إسقاط العضوية',    'label_en' => 'Membership Dropped',  'type' => 'terminal'],
                ],
                'transitions' => [
                    ['name' => 'send_notification', 'from' => 'renewal_due',       'to' => 'notification_sent', 'guards' => [], 'trigger' => 'automatic', 'actions' => [['type' => 'event', 'value' => 'subscription.notification_sent']]],
                    ['name' => 'pay',               'from' => 'notification_sent', 'to' => 'paid',              'guards' => [['type' => 'condition', 'value' => 'has_payment_receipt']], 'actions' => [['type' => 'event', 'value' => 'subscription.paid']]],
                    ['name' => 'mark_overdue',      'from' => 'notification_sent', 'to' => 'overdue',           'guards' => [['type' => 'timeout', 'days' => 90]], 'trigger' => 'automatic', 'actions' => [['type' => 'event', 'value' => 'subscription.overdue']]],
                    ['name' => 'apply_fine',        'from' => 'overdue',           'to' => 'fine_applied',      'guards' => [], 'trigger' => 'automatic', 'actions' => [['type' => 'event', 'value' => 'subscription.fine_applied']]],
                    ['name' => 'pay_with_fine',     'from' => 'fine_applied',      'to' => 'paid_with_fine',    'guards' => [['type' => 'condition', 'value' => 'has_payment_receipt']], 'actions' => [['type' => 'event', 'value' => 'subscription.paid_with_fine']]],
                    ['name' => 'drop_membership',   'from' => 'fine_applied',      'to' => 'membership_dropped','guards' => [['type' => 'condition', 'value' => 'five_years_unpaid']], 'trigger' => 'automatic', 'actions' => [['type' => 'event', 'value' => 'member.dropped']]],
                ],
            ], JSON_UNESCAPED_UNICODE),
        ],
        [
            'workflow_code' => 'transfer_separation',
            'name_ar'       => 'تحويل / فصل',
            'name_en'       => 'Transfer / Separation',
            'description_ar' => 'دورة عمل تحويل أو فصل عضوية',
            'definition_json' => json_encode([
                'states' => [
                    'request_submitted' => ['label_ar' => 'تم تقديم الطلب',      'label_en' => 'Request Submitted',  'type' => 'initial'],
                    'under_review'      => ['label_ar' => 'تحت المراجعة',        'label_en' => 'Under Review',       'type' => 'intermediate'],
                    'board_approved'    => ['label_ar' => 'موافقة مجلس الأمناء', 'label_en' => 'Board Approved',     'type' => 'intermediate'],
                    'board_rejected'    => ['label_ar' => 'رفض مجلس الأمناء',    'label_en' => 'Board Rejected',     'type' => 'terminal'],
                    'fee_calculated'    => ['label_ar' => 'تم حساب الرسوم',      'label_en' => 'Fee Calculated',     'type' => 'intermediate'],
                    'fee_paid'          => ['label_ar' => 'تم سداد الرسوم',      'label_en' => 'Fee Paid',           'type' => 'intermediate'],
                    'archived'          => ['label_ar' => 'تم الأرشفة',          'label_en' => 'Archived',           'type' => 'intermediate'],
                    'new_created'       => ['label_ar' => 'تم إنشاء الجديد',     'label_en' => 'New Created',        'type' => 'intermediate'],
                    'completed'         => ['label_ar' => 'مكتمل',               'label_en' => 'Completed',          'type' => 'terminal'],
                ],
                'transitions' => [
                    ['name' => 'start_review',     'from' => 'request_submitted', 'to' => 'under_review',   'guards' => [['type' => 'permission', 'value' => 'transfer.initiate']], 'actions' => []],
                    ['name' => 'board_approve',    'from' => 'under_review',      'to' => 'fee_calculated', 'guards' => [['type' => 'permission', 'value' => 'transfer.approve']],  'actions' => [['type' => 'event', 'value' => 'transfer.approved']]],
                    ['name' => 'board_reject',     'from' => 'under_review',      'to' => 'board_rejected', 'guards' => [['type' => 'permission', 'value' => 'transfer.approve']],  'actions' => [['type' => 'event', 'value' => 'transfer.rejected']]],
                    ['name' => 'record_payment',   'from' => 'fee_calculated',    'to' => 'fee_paid',       'guards' => [['type' => 'condition', 'value' => 'has_payment_receipt']], 'actions' => []],
                    ['name' => 'archive_old',      'from' => 'fee_paid',          'to' => 'archived',       'guards' => [], 'actions' => [['type' => 'event', 'value' => 'transfer.archived']]],
                    ['name' => 'create_new',       'from' => 'archived',          'to' => 'new_created',    'guards' => [], 'actions' => [['type' => 'event', 'value' => 'transfer.new_created']]],
                    ['name' => 'complete',          'from' => 'new_created',       'to' => 'completed',      'guards' => [], 'actions' => [['type' => 'event', 'value' => 'transfer.completed']]],
                ],
            ], JSON_UNESCAPED_UNICODE),
        ],
        [
            'workflow_code' => 'violation_penalty',
            'name_ar'       => 'المخالفات والعقوبات',
            'name_en'       => 'Violation & Penalty',
            'description_ar' => 'دورة عمل المخالفات والعقوبات والتظلم',
            'definition_json' => json_encode([
                'states' => [
                    'violation_reported'  => ['label_ar' => 'تم الإبلاغ عن مخالفة', 'label_en' => 'Violation Reported',  'type' => 'initial'],
                    'under_review'        => ['label_ar' => 'تحت المراجعة',         'label_en' => 'Under Review',        'type' => 'intermediate'],
                    'penalty_decided'     => ['label_ar' => 'تم تحديد العقوبة',     'label_en' => 'Penalty Decided',     'type' => 'intermediate'],
                    'penalty_active'      => ['label_ar' => 'العقوبة سارية',        'label_en' => 'Penalty Active',      'type' => 'intermediate'],
                    'appealed'            => ['label_ar' => 'تم التظلم',            'label_en' => 'Appealed',            'type' => 'intermediate'],
                    'appeal_reviewed'     => ['label_ar' => 'تم مراجعة التظلم',     'label_en' => 'Appeal Reviewed',     'type' => 'intermediate'],
                    'penalty_upheld'      => ['label_ar' => 'تم تأييد العقوبة',     'label_en' => 'Penalty Upheld',      'type' => 'terminal'],
                    'penalty_modified'    => ['label_ar' => 'تم تعديل العقوبة',     'label_en' => 'Penalty Modified',    'type' => 'terminal'],
                    'penalty_cancelled'   => ['label_ar' => 'تم إلغاء العقوبة',     'label_en' => 'Penalty Cancelled',   'type' => 'terminal'],
                    'dismissed'           => ['label_ar' => 'تم رفض البلاغ',        'label_en' => 'Dismissed',           'type' => 'terminal'],
                    'resolved'            => ['label_ar' => 'تم الحل',              'label_en' => 'Resolved',            'type' => 'terminal'],
                ],
                'transitions' => [
                    ['name' => 'start_review',      'from' => 'violation_reported', 'to' => 'under_review',     'guards' => [['type' => 'permission', 'value' => 'fine.view']],   'actions' => []],
                    ['name' => 'dismiss',            'from' => 'under_review',      'to' => 'dismissed',        'guards' => [['type' => 'permission', 'value' => 'fine.impose']], 'actions' => [['type' => 'event', 'value' => 'violation.dismissed']]],
                    ['name' => 'decide_penalty',     'from' => 'under_review',      'to' => 'penalty_decided',  'guards' => [['type' => 'permission', 'value' => 'fine.impose']], 'actions' => [['type' => 'event', 'value' => 'penalty.decided']]],
                    ['name' => 'activate_penalty',   'from' => 'penalty_decided',   'to' => 'penalty_active',   'guards' => [], 'actions' => [['type' => 'event', 'value' => 'penalty.activated']]],
                    ['name' => 'submit_appeal',      'from' => 'penalty_active',    'to' => 'appealed',         'guards' => [['type' => 'condition', 'value' => 'within_appeal_window']], 'actions' => [['type' => 'event', 'value' => 'penalty.appealed']]],
                    ['name' => 'resolve_no_appeal',  'from' => 'penalty_active',    'to' => 'resolved',         'guards' => [['type' => 'timeout', 'days' => 15]], 'trigger' => 'automatic', 'actions' => [['type' => 'event', 'value' => 'penalty.resolved']]],
                    ['name' => 'review_appeal',      'from' => 'appealed',          'to' => 'appeal_reviewed',  'guards' => [['type' => 'permission', 'value' => 'fine.impose']], 'actions' => []],
                    ['name' => 'uphold_penalty',     'from' => 'appeal_reviewed',   'to' => 'penalty_upheld',   'guards' => [['type' => 'permission', 'value' => 'fine.impose']], 'actions' => [['type' => 'event', 'value' => 'penalty.upheld']]],
                    ['name' => 'modify_penalty',     'from' => 'appeal_reviewed',   'to' => 'penalty_modified', 'guards' => [['type' => 'permission', 'value' => 'fine.impose']], 'actions' => [['type' => 'event', 'value' => 'penalty.modified']]],
                    ['name' => 'cancel_penalty',     'from' => 'appeal_reviewed',   'to' => 'penalty_cancelled','guards' => [['type' => 'permission', 'value' => 'fine.waive']],  'actions' => [['type' => 'event', 'value' => 'penalty.cancelled']]],
                ],
            ], JSON_UNESCAPED_UNICODE),
        ],
    ];

    foreach ($definitions as $def) {
        $existing = $db->selectOne("SELECT id FROM workflow_definitions WHERE workflow_code = ?", [$def['workflow_code']]);
        if ($existing) {
            continue;
        }
        $db->insert('workflow_definitions', [
            'workflow_code'   => $def['workflow_code'],
            'name_ar'         => $def['name_ar'],
            'name_en'         => $def['name_en'],
            'description_ar'  => $def['description_ar'],
            'definition_json' => $def['definition_json'],
            'version'         => 1,
            'is_active'       => 1,
            'created_at'      => $ts,
            'updated_at'      => $ts,
        ]);
    }
};