<?php

namespace Database\Seeders;

use App\Models\EmpTeam;
use App\Models\User;
use App\Models\Workspace;
use App\Models\Role;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class CustomerConstructionRolesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Get all customers (user_type = 2) that are active and not deleted
        $customers = User::where('user_type', config('constants.user_types.customer'))
            ->where('active_status', 1)
            ->where('del', '0')
            ->get();

        if ($customers->isEmpty()) {
            echo "No customers found to seed roles for.\n";
            return;
        }

        echo "Found {$customers->count()} customers. Starting to seed construction roles...\n";

        foreach ($customers as $customer) {
            try {
                // Get the customer's workspace
                $workspace = Workspace::where('customer_id', $customer->id)->first();

                if (!$workspace) {
                    echo "Warning: No workspace found for customer {$customer->name} (ID: {$customer->id}). Skipping...\n";
                    continue;
                }

                // Create/update construction roles for this customer
                $createdRoles = $this->createConstructionRoles($customer->id, $workspace->id);

                echo "Successfully created/updated " . count($createdRoles) . " roles for customer {$customer->name} (ID: {$customer->id})\n";
            } catch (\Exception $e) {
                echo "Error processing customer {$customer->name} (ID: {$customer->id}): " . $e->getMessage() . "\n";
            }
        }

        echo "Finished seeding construction roles for all customers.\n";
    }

    /**
     * Create construction roles for a specific customer and workspace
     * This function mirrors the createConstructionRoles function from HelperTrait
     */
    public function createConstructionRoles($customer_id, $workspace_id, $created_by = null)
    {
        // Roles are now global and managed by super admin via RoleSeeder
        // This function now only creates default team for customer/workspace
        $created_by = $created_by ?? $customer_id;

        // Create a default team if it doesn't exist
        $this->createDefaultTeam($customer_id, $workspace_id, $created_by);

        // Return empty array as roles are no longer created per customer
        return [];
    }

    /**
     * Clean up duplicate roles (same title/code combination)
     * DEPRECATED: Roles are now global, this method is no longer needed
     */
    private function cleanupDuplicateRoles($customer_id, $workspace_id)
    {
        // Roles are now global - no cleanup needed per customer/workspace
        return;
    }

    private function createDefaultTeam($customer_id, $workspace_id, $created_by = null)
    {
        $created_by = $created_by ?? $customer_id;

        // Check if a default team already exists for this customer/workspace
        $existingTeam = EmpTeam::where('customer_id', $customer_id)
            ->where('workspace_id', $workspace_id)
            ->where('del', '0')
            ->first();

        if (!$existingTeam) {
            // Create a default team with null supervisor (since employees might not exist yet)
            EmpTeam::create([
                'title' => 'Default Team',
                'supervisor' => null, // Will be updated later when employees are created
                'description' => 'Default team created automatically during role setup',
                'customer_id' => $customer_id,
                'workspace_id' => $workspace_id,
                'created_by' => $created_by,
                'del' => '0',
            ]);
        }
    }
}