<?php

declare(strict_types=1);

final class HyroLeadActivityRepository
{
    public function __construct(
        private readonly PDO $database
    ) {
    }

    public function create(
        int $leadId,
        string $type,
        string $title,
        ?string $description = null,
        ?string $oldValue = null,
        ?string $newValue = null,
        ?int $userId = null,
        ?string $userName = null
    ): int {
        $statement = $this->database->prepare(
            '
            INSERT INTO hyro_lead_activities
            (
                lead_id,
                activity_type,
                activity_title,
                activity_description,
                old_value,
                new_value,
                created_by_user_id,
                created_by_name,
                created_at
            )
            VALUES
            (
                :lead_id,
                :activity_type,
                :activity_title,
                :activity_description,
                :old_value,
                :new_value,
                :created_by_user_id,
                :created_by_name,
                :created_at
            )
            '
        );

        $statement->execute([
            'lead_id' => $leadId,
            'activity_type' => $type,
            'activity_title' => $title,
            'activity_description' => $description,
            'old_value' => $oldValue,
            'new_value' => $newValue,
            'created_by_user_id' => $userId,
            'created_by_name' => $userName,
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        return (int) $this->database->lastInsertId();
    }

    public function allForLead(int $leadId): array
    {
        $statement = $this->database->prepare(
            '
            SELECT
                id,
                activity_type,
                activity_title,
                activity_description,
                old_value,
                new_value,
                created_by_name,
                created_at
            FROM hyro_lead_activities
            WHERE lead_id = :lead_id
            ORDER BY id DESC
            '
        );

        $statement->execute([
            'lead_id' => $leadId,
        ]);

        return $statement->fetchAll();
    }
}
