<?php
namespace Espo\Custom\Api\CPuls;

use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\NotFound;

class AktiviereTeams implements Action
{
    public function __construct(
        private \Espo\ORM\EntityManager $entityManager,
        private \Espo\Core\Utils\Log $log
    ) {}
    
    public function process(Request $request): Response
    {
        $id = $request->getRouteParam('id');
        
        if (!$id) {
            throw new BadRequest('ID fehlt');
        }
        
        $puls = $this->entityManager->getEntity('CPuls', $id);
        
        if (!$puls) {
            throw new NotFound('Puls nicht gefunden');
        }
        
        $data = $request->getParsedBody();
        
        // 1. Update Puls
        $puls->set([
            'kiAnalyse' => $data->kiAnalyse ?? null,
            'zusammenfassung' => $data->zusammenfassung ?? null,
            'status' => $data->status ?? 'Bereit',
            'syncStatus' => $data->syncStatus ?? 'clean'
        ]);
        
        $this->entityManager->saveEntity($puls);
        
        // 2. Lösche alte Zuordnungen (soft delete - setze inaktiv)
        $this->entityManager
            ->getQueryBuilder()
            ->update()
            ->in('CPulsTeamZuordnung')
            ->set(['aktiv' => false])
            ->where(['pulsId' => $id])
            ->execute();
        
        // 3. Erstelle neue Zuordnungen
        if (isset($data->teams) && is_array($data->teams)) {
            foreach ($data->teams as $teamData) {
                $teamId = $teamData->teamId ?? null;
                
                if (!$teamId) {
                    $this->log->warning("Team-ID fehlt in teams-Array");
                    continue;
                }
                
                // Prüfe ob bereits existiert
                $existing = $this->entityManager
                    ->getRDBRepository('CPulsTeamZuordnung')
                    ->where([
                        'pulsId' => $id,
                        'teamId' => $teamId
                    ])
                    ->findOne();
                
                if ($existing) {
                    // Reaktiviere
                    $existing->set([
                        'aktiv' => true,
                        'abgeschlossen' => false,
                        'prioritaet' => $teamData->prioritaet ?? 'Normal'
                    ]);
                    $this->entityManager->saveEntity($existing);
                } else {
                    // Erstelle neu
                    $zuordnung = $this->entityManager->createEntity('CPulsTeamZuordnung', [
                        'pulsId' => $id,
                        'teamId' => $teamId,
                        'aktiv' => true,
                        'abgeschlossen' => false,
                        'prioritaet' => $teamData->prioritaet ?? 'Normal'
                    ]);
                }
            }
        }
        
        $this->log->info("Teams aktiviert für Puls {$id}");
        
        return Response::json([
            'success' => true,
            'pulsId' => $id
        ]);
    }
}
