<?php

namespace App\Services;

use App\Models\ActivityLogModel;
use App\Models\ActivityLogType;
use App\Repositories\ActivityLogRepository;
use App\Repositories\UserRepo;
use PDO;

class ActivityLogService
{

  private ActivityLogRepository $repository;
  private UserRepo $userRepo;
  public function __construct()
  {
    $this->repository = new ActivityLogRepository();
    $this->userRepo = new UserRepo();
  }

  public function create(
    PDO $connection,
    int $userId,
    ?int $ticketId,
    ?int $targetUserId,
    ?string $status,
    ActivityLogType $log,
    ?string $ipAddress = null
  ): void {

    $aktivitas = $log->message();

    if ($targetUserId) {
      $user = $this->userRepo->findById($targetUserId);
      $aktivitas = str_replace('#namaUser', $user->getNama(), $aktivitas);
    }

    if ($status) {
      $aktivitas = str_replace('#status', $status, $aktivitas);
    }

    $this->repository->insert(
      $connection,
      new ActivityLogModel(
        id: null,
        ticketId: $ticketId,
        userId: $userId,
        aktivitas: $aktivitas,
        logType: $log->value,
        ipAddress: $ipAddress,
        tanggalAktivitas: null
      )
    );
  }

  public function findByTicketId(int $ticketId): array
  {
    return $this->repository->findByTicketId($ticketId);
  }
}
