<?php

namespace App\Services;

use App\Contracts\AcademicCalendarRepositoryInterface;
use App\Contracts\AuditLogServiceInterface;
use App\Models\AcademicEvent;
use App\Models\AcademicYear;
use App\Models\SchoolHoliday;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Auth;

class AcademicCalendarService
{
    public function __construct(
        protected AcademicCalendarRepositoryInterface $calendarRepository,
        protected AuditLogServiceInterface $auditLogService
    ) {}

    public function getAllAcademicYears(): Collection
    {
        return $this->calendarRepository->getAllAcademicYears();
    }

    public function getAllHolidays(): Collection
    {
        return $this->calendarRepository->getAllHolidays();
    }

    public function getAllEvents(): Collection
    {
        return $this->calendarRepository->getAllEvents();
    }

    public function isHolidayOrWeekend(string $date): bool
    {
        return $this->calendarRepository->isHolidayOrWeekend($date);
    }

    public function createAcademicYear(array $data): AcademicYear
    {
        $year = $this->calendarRepository->createAcademicYear($data);
        $user = Auth::user();
        $this->auditLogService->log($user, 'ACADEMIC_YEAR_CREATED', "Menambahkan Tahun Akademik: {$year->name}");

        return $year;
    }

    public function createHoliday(array $data): SchoolHoliday
    {
        $holiday = $this->calendarRepository->createHoliday($data);
        $user = Auth::user();
        $this->auditLogService->log($user, 'SCHOOL_HOLIDAY_CREATED', "Menambahkan Hari Libur: {$holiday->name} ({$holiday->date})");

        return $holiday;
    }

    public function createEvent(array $data): AcademicEvent
    {
        $event = $this->calendarRepository->createEvent($data);
        $user = Auth::user();
        $this->auditLogService->log($user, 'ACADEMIC_EVENT_CREATED', "Menambahkan kegiatan: {$event->title}");

        return $event;
    }

    public function deleteEvent(int $id): bool
    {
        $deleted = $this->calendarRepository->deleteEvent($id);
        if ($deleted) {
            $user = Auth::user();
            $this->auditLogService->log($user, 'ACADEMIC_EVENT_DELETED', "Menghapus kegiatan akademik ID: {$id}");
        }

        return $deleted;
    }
}
