<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\Workspace;
use App\Enums\StatusEnum;
use Illuminate\Database\Seeder;
use App\Helpers\InstallationLogger;

class WorkspaceSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        InstallationLogger::info('WorkspaceSeeder: Starting workspace seeding');

        try {
            // Find the admin user (owner)
            $adminUser = User::where('owner', StatusEnum::true->status())->first();

            if (!$adminUser) {
                InstallationLogger::error('WorkspaceSeeder: No admin user found to create workspace');
                throw new \Exception('Admin user not found - cannot create workspace');
            }

            InstallationLogger::info("WorkspaceSeeder: Found admin user: {$adminUser->email}");

            // Check if workspace already exists for this user
            $existingWorkspace = Workspace::where('user_id', $adminUser->id)->first();

            if ($existingWorkspace) {
                InstallationLogger::info("WorkspaceSeeder: Workspace already exists for user: {$existingWorkspace->name}");
                return;
            }

            // Create default workspace for admin user
            $workspace = Workspace::create([
                'user_id' => $adminUser->id,
                'name' => $adminUser->name . "'s Workspace",
                'email' => $adminUser->email,
                'status' => StatusEnum::true->status(),
                'is_default' => StatusEnum::true->status(),
                'is_current' => StatusEnum::true->status(),
            ]);

            InstallationLogger::info("WorkspaceSeeder: Created workspace: {$workspace->name} (ID: {$workspace->id})");

            // Update user's current workspace
            $adminUser->update([
                'current_workspace_id' => $workspace->id
            ]);

            InstallationLogger::info("WorkspaceSeeder: Updated admin user's current workspace to: {$workspace->id}");

        } catch (\Exception $e) {
            InstallationLogger::error('WorkspaceSeeder: Failed with error: ' . $e->getMessage());
            InstallationLogger::error('WorkspaceSeeder: File: ' . $e->getFile() . ' Line: ' . $e->getLine());
            InstallationLogger::debug('WorkspaceSeeder: Stack trace: ' . $e->getTraceAsString());
            throw $e;
        }

        InstallationLogger::info('WorkspaceSeeder: Completed successfully');
    }
}