<?php

declare(strict_types=1);

namespace Database\Seeders;

use PDO;

final class OrgStructureSeeder implements SeederInterface
{
    public function run(PDO $pdo): void
    {
        $businessLineIds = $pdo->query('SELECT slug, id FROM business_lines')->fetchAll(PDO::FETCH_KEY_PAIR);

        $departments = [
            ['slug' => 'homecare', 'name' => 'Homecare Operations', 'description' => 'Caregiving staff, scheduling, and client care quality.'],
            ['slug' => 'janitorial', 'name' => 'Janitorial Operations', 'description' => 'Commercial and residential cleaning crews.'],
            ['slug' => null, 'name' => 'Sales & Growth', 'description' => 'Lead generation and account management across both brands.'],
        ];

        $deptStmt = $pdo->prepare(
            'INSERT INTO departments (business_line_id, name, description, created_at, updated_at)
             VALUES (:bl, :name, :description, NOW(), NOW())'
        );

        $deptIds = [];
        foreach ($departments as $dept) {
            $exists = $pdo->prepare('SELECT id FROM departments WHERE name = :name');
            $exists->execute(['name' => $dept['name']]);
            $existingId = $exists->fetchColumn();

            if ($existingId !== false) {
                $deptIds[$dept['name']] = (int) $existingId;
                continue;
            }

            $blId = isset($dept['slug']) ? ($businessLineIds[$dept['slug']] ?? null) : null;
            $deptStmt->execute(['bl' => $blId, 'name' => $dept['name'], 'description' => $dept['description']]);
            $deptIds[$dept['name']] = (int) $pdo->lastInsertId();
        }

        echo '  seeded ' . count($departments) . " departments\n";

        $teams = [
            ['name' => 'Caregiver Team A', 'department' => 'Homecare Operations', 'slug' => 'homecare'],
            ['name' => 'Cleaning Crew — Downtown', 'department' => 'Janitorial Operations', 'slug' => 'janitorial'],
            ['name' => 'Sales Team', 'department' => 'Sales & Growth', 'slug' => null],
        ];

        $teamStmt = $pdo->prepare(
            'INSERT INTO teams (department_id, business_line_id, name, description, created_at, updated_at)
             VALUES (:dept_id, :bl, :name, :description, NOW(), NOW())'
        );

        $teamCount = 0;
        foreach ($teams as $team) {
            $exists = $pdo->prepare('SELECT id FROM teams WHERE name = :name');
            $exists->execute(['name' => $team['name']]);
            if ($exists->fetchColumn() !== false) {
                continue;
            }

            $blId = $team['slug'] ? ($businessLineIds[$team['slug']] ?? null) : null;
            $teamStmt->execute([
                'dept_id' => $deptIds[$team['department']] ?? null,
                'bl' => $blId,
                'name' => $team['name'],
                'description' => "Team under {$team['department']}.",
            ]);
            $teamCount++;
        }

        echo "  seeded {$teamCount} teams\n";
    }
}
