from __future__ import annotations

from datetime import datetime

from sqlalchemy import select

from supply_infra.db.models.scheduler_job_execution import SchedulerJobExecution
from supply_infra.db.repositories.base import BaseRepository


class SchedulerJobExecutionRepository(BaseRepository[SchedulerJobExecution]):
    model = SchedulerJobExecution

    def log_event(
        self,
        *,
        run_id: str,
        job_name: str,
        status: str,
        event_time: datetime,
        job_id: str | None = None,
        biz_dt: str | None = None,
        started_at: datetime | None = None,
        finished_at: datetime | None = None,
        duration_seconds: float | None = None,
        error_message: str | None = None,
        detail: str | None = None,
    ) -> SchedulerJobExecution:
        entity = SchedulerJobExecution(
            run_id=run_id,
            job_name=job_name,
            job_id=job_id,
            status=status,
            event_time=event_time,
            biz_dt=biz_dt,
            started_at=started_at,
            finished_at=finished_at,
            duration_seconds=duration_seconds,
            error_message=error_message,
            detail=detail,
        )
        return self.add(entity)

    def list_recent(self, *, limit: int = 50) -> list[SchedulerJobExecution]:
        stmt = (
            select(SchedulerJobExecution)
            .order_by(SchedulerJobExecution.event_time.desc(), SchedulerJobExecution.id.desc())
            .limit(limit)
        )
        return list(self.session.scalars(stmt).all())
