<?php

declare(strict_types=1);

namespace App\Shared\Infrastructure\Mcp;

use App\Module\Absence\Domain\Entity\AbsenceBalance;
use App\Module\Absence\Domain\Entity\AbsencePolicy;
use App\Module\Absence\Domain\Entity\AbsenceRequest;
use App\Module\Core\Domain\Entity\User;
use App\Module\Directory\Domain\Entity\Address;
use App\Module\Directory\Domain\Entity\Client;
use App\Module\Directory\Domain\Entity\CommercialReport;
use App\Module\Directory\Domain\Entity\Contact;
use App\Module\Directory\Domain\Entity\Prestataire;
use App\Module\Directory\Domain\Entity\Prospect;
use App\Module\Directory\Domain\Entity\ReportDocument;
use App\Module\ProjectManagement\Domain\Entity\Project;
use App\Module\ProjectManagement\Domain\Entity\TaskDocument;
use App\Module\ProjectManagement\Domain\Entity\TaskEffort;
use App\Module\ProjectManagement\Domain\Entity\TaskGroup;
use App\Module\ProjectManagement\Domain\Entity\TaskPriority;
use App\Module\ProjectManagement\Domain\Entity\TaskStatus;
use App\Module\ProjectManagement\Domain\Entity\TaskTag;
use App\Module\TimeTracking\Domain\Entity\TimeEntry;
use App\Shared\Domain\Contract\ClientInterface;
use App\Shared\Domain\Contract\ProjectInterface;
use App\Shared\Domain\Contract\TaskInterface;
use App\Shared\Domain\Contract\TaskTagInterface;
use App\Shared\Domain\Contract\UserInterface;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\EntityNotFoundException;

/**
 * Shared serialization helpers for MCP tools.
 *
 * Keeps JSON output consistent across all tools.
 */
final class Serializer
{
    /**
     * @return array{id: ?int, code: ?string, name: ?string}
     */
    public static function projectRef(ProjectInterface $project): array
    {
        return [
            'id'   => $project->getId(),
            'code' => $project->getCode(),
            'name' => $project->getName(),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public static function project(Project $project): array
    {
        return [
            'id'          => $project->getId(),
            'code'        => $project->getCode(),
            'name'        => $project->getName(),
            'description' => $project->getDescription(),
            'color'       => $project->getColor(),
            'client'      => self::clientRef($project->getClient()),
            'archived'    => $project->isArchived(),
        ];
    }

    /**
     * @return null|array{id: ?int, label: ?string, color: ?string}
     */
    public static function status(?TaskStatus $status): ?array
    {
        if (null === $status) {
            return null;
        }

        return [
            'id'    => $status->getId(),
            'label' => $status->getLabel(),
            'color' => $status->getColor(),
        ];
    }

    /**
     * @return null|array{id: ?int, label: ?string, color: ?string, isFinal: bool}
     */
    public static function statusFull(?TaskStatus $status): ?array
    {
        if (null === $status) {
            return null;
        }

        return [
            'id'      => $status->getId(),
            'label'   => $status->getLabel(),
            'color'   => $status->getColor(),
            'isFinal' => $status->getIsFinal(),
        ];
    }

    /**
     * @return null|array{id: ?int, label: ?string, color: ?string}
     */
    public static function priority(?TaskPriority $priority): ?array
    {
        if (null === $priority) {
            return null;
        }

        return [
            'id'    => $priority->getId(),
            'label' => $priority->getLabel(),
            'color' => $priority->getColor(),
        ];
    }

    /**
     * @return null|array{id: ?int, label: ?string}
     */
    public static function effort(?TaskEffort $effort): ?array
    {
        if (null === $effort) {
            return null;
        }

        return [
            'id'    => $effort->getId(),
            'label' => $effort->getLabel(),
        ];
    }

    /**
     * @return null|array{id: ?int, username: ?string}
     */
    public static function user(?UserInterface $user): ?array
    {
        if (null === $user) {
            return null;
        }

        return [
            'id'       => $user->getId(),
            'username' => $user->getUsername(),
        ];
    }

    /**
     * @param Collection<int, UserInterface> $users
     *
     * @return list<array{id: ?int, username: ?string}>
     */
    public static function users(Collection $users): array
    {
        return $users->map(fn (UserInterface $u) => [
            'id'       => $u->getId(),
            'username' => $u->getUsername(),
        ])->toArray();
    }

    /**
     * @return null|array{id: ?int, title: ?string, color: ?string}
     */
    public static function group(?TaskGroup $group): ?array
    {
        if (null === $group) {
            return null;
        }

        return [
            'id'    => $group->getId(),
            'title' => $group->getTitle(),
            'color' => $group->getColor(),
        ];
    }

    /**
     * @return null|array{id: ?int, title: ?string}
     */
    public static function groupRef(?TaskGroup $group): ?array
    {
        if (null === $group) {
            return null;
        }

        return [
            'id'    => $group->getId(),
            'title' => $group->getTitle(),
        ];
    }

    /**
     * Full group serialization for MCP group tools (includes description, project, archived).
     *
     * @return array<string, mixed>
     */
    public static function groupFull(TaskGroup $group): array
    {
        return [
            'id'          => $group->getId(),
            'title'       => $group->getTitle(),
            'description' => $group->getDescription(),
            'color'       => $group->getColor(),
            'project'     => self::projectRef($group->getProject()),
            'archived'    => $group->isArchived(),
        ];
    }

    /**
     * @param Collection<int, TaskTagInterface> $tags
     *
     * @return list<array{id: ?int, label: ?string}>
     */
    public static function tags(Collection $tags): array
    {
        return $tags->map(fn (TaskTagInterface $t) => [
            'id'    => $t->getId(),
            'label' => $t->getLabel(),
        ])->toArray();
    }

    /**
     * @param Collection<int, TaskTag> $tags
     *
     * @return list<array{id: ?int, label: ?string, color: ?string}>
     */
    public static function tagsWithColor(Collection $tags): array
    {
        return $tags->map(fn (TaskTag $t) => [
            'id'    => $t->getId(),
            'label' => $t->getLabel(),
            'color' => $t->getColor(),
        ])->toArray();
    }

    /**
     * Compute duration in minutes between two timestamps, or null if still active.
     */
    public static function durationMinutes(TimeEntry $entry): ?int
    {
        $started = $entry->getStartedAt();
        $stopped = $entry->getStoppedAt();

        if (null === $stopped || null === $started) {
            return null;
        }

        return (int) round(($stopped->getTimestamp() - $started->getTimestamp()) / 60);
    }

    /**
     * @return null|array{id: ?int, number: ?int, title: ?string}
     */
    public static function taskRef(?TaskInterface $task): ?array
    {
        if (null === $task) {
            return null;
        }

        return [
            'id'     => $task->getId(),
            'number' => $task->getNumber(),
            'title'  => $task->getTitle(),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public static function timeEntry(TimeEntry $entry): array
    {
        return [
            'id'          => $entry->getId(),
            'title'       => $entry->getTitle(),
            'description' => $entry->getDescription(),
            'startedAt'   => $entry->getStartedAt()?->format('c'),
            'stoppedAt'   => $entry->getStoppedAt()?->format('c'),
            'duration'    => self::durationMinutes($entry),
            'user'        => self::user($entry->getUser()),
            'project'     => $entry->getProject() ? self::projectRef($entry->getProject()) : null,
            'task'        => self::taskRef($entry->getTask()),
            'tags'        => self::tags($entry->getTags()),
        ];
    }

    /**
     * @param Collection<int, TaskDocument> $documents
     *
     * @return list<array<string, mixed>>
     */
    public static function documents(Collection $documents): array
    {
        return $documents->map(fn (TaskDocument $doc) => [
            'id'           => $doc->getId(),
            'originalName' => $doc->getOriginalName(),
            'mimeType'     => $doc->getMimeType(),
            'size'         => $doc->getSize(),
            'createdAt'    => $doc->getCreatedAt()?->format('c'),
            'uploadedBy'   => self::user($doc->getUploadedBy()),
        ])->toArray();
    }

    /**
     * @return array<string, mixed>
     */
    public static function absenceRequest(AbsenceRequest $r): array
    {
        return [
            'id'                    => $r->getId(),
            'user'                  => self::user($r->getUser()),
            'type'                  => $r->getType()?->value,
            'typeLabel'             => $r->getType()?->label(),
            'startDate'             => $r->getStartDate()?->format('Y-m-d'),
            'endDate'               => $r->getEndDate()?->format('Y-m-d'),
            'startHalfDay'          => $r->getStartHalfDay()?->value,
            'endHalfDay'            => $r->getEndHalfDay()?->value,
            'countedDays'           => $r->getCountedDays(),
            'reason'                => $r->getReason(),
            'status'                => $r->getStatus()->value,
            'statusLabel'           => $r->getStatus()->label(),
            'rejectionReason'       => $r->getRejectionReason(),
            'justificationFileName' => $r->getJustificationFileName(),
            'createdAt'             => $r->getCreatedAt()?->format('c'),
            'reviewedAt'            => $r->getReviewedAt()?->format('c'),
            'reviewedBy'            => self::user($r->getReviewedBy()),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public static function absencePolicy(AbsencePolicy $p): array
    {
        return [
            'id'                    => $p->getId(),
            'type'                  => $p->getType()->value,
            'typeLabel'             => $p->getType()->label(),
            'daysPerYear'           => $p->getDaysPerYear(),
            'daysPerEvent'          => $p->getDaysPerEvent(),
            'justificationRequired' => $p->isJustificationRequired(),
            'noticeDays'            => $p->getNoticeDays(),
            'countWorkingDaysOnly'  => $p->isCountWorkingDaysOnly(),
            'active'                => $p->isActive(),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public static function absenceBalance(AbsenceBalance $b): array
    {
        return [
            'id'            => $b->getId(),
            'user'          => self::user($b->getUser()),
            'type'          => $b->getType()->value,
            'typeLabel'     => $b->getType()->label(),
            'period'        => $b->getPeriod(),
            'acquired'      => $b->getAcquired(),
            'acquiring'     => $b->getAcquiring(),
            'taken'         => $b->getTaken(),
            'pending'       => $b->getPending(),
            'acquiredTotal' => $b->getAcquiredTotal(),
            'available'     => $b->getAvailable(),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public static function client(Client $c): array
    {
        return [
            'id'      => $c->getId(),
            'name'    => $c->getName(),
            'email'   => $c->getEmail(),
            'phone'   => $c->getPhone(),
            'website' => $c->getWebsite(),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public static function prestataire(Prestataire $p): array
    {
        return [
            'id'      => $p->getId(),
            'name'    => $p->getName(),
            'email'   => $p->getEmail(),
            'phone'   => $p->getPhone(),
            'website' => $p->getWebsite(),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public static function contact(Contact $c): array
    {
        return [
            'id'             => $c->getId(),
            'firstName'      => $c->getFirstName(),
            'lastName'       => $c->getLastName(),
            'jobTitle'       => $c->getJobTitle(),
            'email'          => $c->getEmail(),
            'phonePrimary'   => $c->getPhonePrimary(),
            'phoneSecondary' => $c->getPhoneSecondary(),
            'clientId'       => $c->getClient()?->getId(),
            'prospectId'     => $c->getProspect()?->getId(),
            'prestataireId'  => $c->getPrestataire()?->getId(),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public static function address(Address $a): array
    {
        return [
            'id'               => $a->getId(),
            'label'            => $a->getLabel(),
            'street'           => $a->getStreet(),
            'streetComplement' => $a->getStreetComplement(),
            'postalCode'       => $a->getPostalCode(),
            'city'             => $a->getCity(),
            'country'          => $a->getCountry(),
            'clientId'         => $a->getClient()?->getId(),
            'prospectId'       => $a->getProspect()?->getId(),
            'prestataireId'    => $a->getPrestataire()?->getId(),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public static function reportDocument(ReportDocument $d): array
    {
        return [
            'id'           => $d->getId(),
            'originalName' => $d->getOriginalName(),
            'mimeType'     => $d->getMimeType(),
            'size'         => $d->getSize(),
            'createdAt'    => $d->getCreatedAt()?->format('c'),
            'uploadedBy'   => self::user($d->getUploadedBy()),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public static function commercialReport(CommercialReport $r): array
    {
        return [
            'id'            => $r->getId(),
            'subject'       => $r->getSubject(),
            'body'          => $r->getBody(),
            'occurredAt'    => $r->getOccurredAt()?->format('Y-m-d'),
            'type'          => $r->getType()->value,
            'typeLabel'     => $r->getType()->label(),
            'author'        => self::user($r->getAuthor()),
            'clientId'      => $r->getClient()?->getId(),
            'prospectId'    => $r->getProspect()?->getId(),
            'prestataireId' => $r->getPrestataire()?->getId(),
            'documents'     => array_map(
                fn (ReportDocument $d) => self::reportDocument($d),
                $r->getDocuments()->toArray()
            ),
            'createdAt' => $r->getCreatedAt()?->format('c'),
            'updatedAt' => $r->getUpdatedAt()?->format('c'),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public static function prospect(Prospect $p): array
    {
        $client = $p->getConvertedClient();

        return [
            'id'              => $p->getId(),
            'company'         => $p->getCompany(),
            'email'           => $p->getEmail(),
            'phone'           => $p->getPhone(),
            'website'         => $p->getWebsite(),
            'status'          => $p->getStatus()->value,
            'statusLabel'     => $p->getStatus()->label(),
            'source'          => $p->getSource(),
            'notes'           => $p->getNotes(),
            'convertedClient' => null === $client ? null : [
                'id'   => $client->getId(),
                'name' => $client->getName(),
            ],
            'createdAt' => $p->getCreatedAt()?->format('c'),
            'updatedAt' => $p->getUpdatedAt()?->format('c'),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public static function userFull(User $u): array
    {
        return [
            'id'                   => $u->getId(),
            'username'             => $u->getUsername(),
            'roles'                => $u->getRoles(),
            'isEmployee'           => $u->getIsEmployee(),
            'hireDate'             => $u->getHireDate()?->format('Y-m-d'),
            'endDate'              => $u->getEndDate()?->format('Y-m-d'),
            'contractType'         => $u->getContractType()?->value,
            'workTimeRatio'        => $u->getWorkTimeRatio(),
            'annualLeaveDays'      => $u->getAnnualLeaveDays(),
            'referencePeriodStart' => $u->getReferencePeriodStart(),
            'initialLeaveBalance'  => $u->getInitialLeaveBalance(),
        ];
    }

    /**
     * Safely serialize a project's client reference.
     *
     * The client association uses ON DELETE SET NULL, but a stale row may leave
     * a dangling foreign key (e.g. data imported with the constraint disabled).
     * In that case Doctrine returns an uninitialized proxy whose hydration
     * throws EntityNotFoundException; we treat such a reference as absent rather
     * than letting it crash the whole tool.
     *
     * @return null|array{id: ?int, name: ?string}
     */
    private static function clientRef(?ClientInterface $client): ?array
    {
        if (null === $client) {
            return null;
        }

        try {
            return [
                'id'   => $client->getId(),
                'name' => $client->getName(),
            ];
        } catch (EntityNotFoundException) {
            return null;
        }
    }
}
