import { getCheckInTask } from '@/data/check-in'
import { getPoiRepository } from '@/data/poi'
import {
  applyCheckIn,
  type CheckInLocationSnapshot,
  type CheckInProfile,
  type CheckInResult,
} from '@/domain/check-in'
import { loadCheckInProfile, saveCheckInProfile } from './storage'

export function checkInAtPoi(
  poiId: string,
  location: CheckInLocationSnapshot,
  now = Date.now(),
): CheckInResult {
  const poi = getPoiRepository().getPoiById(poiId)
  const task = poi ? getCheckInTask(poi.id) : null
  if (!poi || !task)
    throw new Error('该点位不存在或已下线，暂时无法打卡')
  const result = applyCheckIn(loadCheckInProfile(), poi, location, now, task.radiusMeters)
  saveCheckInProfile(result.profile)
  return result
}

export function getCheckInProfile(): CheckInProfile {
  return loadCheckInProfile()
}
