<?php

namespace Database\Seeders\Dummy;

use App\Models\Members\User;
use App\Models\Tenants\Card;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Crypt;

class DummyCardSeeder extends Seeder
{
    public function run(): void
    {
        $tenantIds = [1, 287]; // 두 테넌트에 생성

        // 각 테넌트별로 TenantUserProfile이 있는 사용자 찾기
        $usersByTenant = [];
        foreach ($tenantIds as $tenantId) {
            $profile = \App\Models\Tenants\TenantUserProfile::where('tenant_id', $tenantId)
                ->whereNotNull('department_id')
                ->first();
            $usersByTenant[$tenantId] = $profile?->user_id ?? User::first()?->id ?? 1;
        }

        $cards = [
            [
                'card_company' => 'shinhan',
                'card_number' => '4532123456781234',
                'expiry_date' => '12/27',
                'card_name' => '법인 신한카드 1',
                'status' => 'active',
            ],
            [
                'card_company' => 'samsung',
                'card_number' => '5412345678901234',
                'expiry_date' => '06/26',
                'card_name' => '법인 삼성카드',
                'status' => 'active',
            ],
            [
                'card_company' => 'kb',
                'card_number' => '9876543210123456',
                'expiry_date' => '03/28',
                'card_name' => 'KB국민 법인카드',
                'status' => 'active',
            ],
            [
                'card_company' => 'hyundai',
                'card_number' => '1234567890123456',
                'expiry_date' => '09/25',
                'card_name' => '현대카드 법인',
                'status' => 'inactive',
            ],
            [
                'card_company' => 'lotte',
                'card_number' => '6789012345678901',
                'expiry_date' => '11/26',
                'card_name' => '롯데카드 법인',
                'status' => 'active',
            ],
        ];

        foreach ($tenantIds as $tenantId) {
            $userId = $usersByTenant[$tenantId];
            foreach ($cards as $cardData) {
                $card = new Card;
                $card->tenant_id = $tenantId;
                $card->card_company = $cardData['card_company'];
                $card->card_number_encrypted = Crypt::encryptString($cardData['card_number']);
                $card->card_number_last4 = substr($cardData['card_number'], -4);
                $card->expiry_date = $cardData['expiry_date'];
                $card->card_name = $cardData['card_name'];
                $card->status = $cardData['status'];
                $card->assigned_user_id = $userId;
                $card->created_by = $userId;
                $card->updated_by = $userId;
                $card->save();
            }
        }

        $this->command->info('DummyCardSeeder: '.(count($cards) * count($tenantIds)).' cards created');
    }
}
