<?php

namespace Database\Seeders;

use App\Models\Expense;
use App\Models\Group;
use App\Models\Person;
use App\Models\Profile;
use App\Models\Activity;
use App\Models\User;
use Illuminate\Database\Seeder;

class DemoWeshareSeeder extends Seeder
{
    public function run(): void
    {
        $user = User::where('email', 'demo@example.com')->first();
        if (! $user) {
            $user = User::factory()->create([
                'email' => 'demo@example.com',
                'name' => 'Demo',
            ]);
        }

        $spaceId = $user->profile?->default_space_id;
        if (! $spaceId) {
            return;
        }

        Profile::where('user_id', $user->id)->update([
            'onboarding_completed_at' => now(),
        ]);

        $me = Person::where('space_id', $spaceId)->where('auth_user_id', $user->id)->first();
        if (! $me) {
            return;
        }

        $group = Group::firstOrCreate(
            ['id' => 'g_demo'],
            [
                'space_id' => $spaceId,
                'name' => 'Home',
                'emoji' => '🏠',
                'type' => 'home',
                'currency' => 'USD',
                'total_expenses' => 0,
                'created_at' => now()->toDateString(),
            ]
        );
        $group->space_id = $spaceId;
        $group->save();
        $group->members()->syncWithoutDetaching([$me->id]);

        Expense::updateOrCreate(
            ['id' => 'e_demo'],
            [
                'space_id' => $spaceId,
                'group_id' => $group->id,
                'shared_list_id' => null,
                'description' => 'Groceries',
                'amount' => 42.50,
                'currency' => 'USD',
                'paid_by_person_id' => $me->id,
                'split_type' => 'equal',
                'split_among' => [
                    ['userId' => $me->id, 'amount' => 42.50],
                ],
                'category' => 'groceries',
                'emoji' => '🛒',
                'expense_date' => now()->toDateString(),
                'is_recurring' => false,
            ]
        );

        Activity::updateOrCreate(
            ['id' => 'a_demo'],
            [
                'space_id' => $spaceId,
                'activity_type' => 'expense',
                'description' => 'added an expense',
                'i18n' => null,
                'user_person_id' => $me->id,
                'amount' => 42.50,
                'group_name' => $group->name,
                'list_name' => null,
                'activity_at' => now(),
            ]
        );
    }
}

