package com.smartoffice.attendance;

import com.smartoffice.common.ApiException;
import com.smartoffice.user.User;
import com.smartoffice.user.UserRepository;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.util.List;

@Service
public class AttendanceService {
    private final AttendanceRepository attendanceRepository;
    private final UserRepository userRepository;

    public AttendanceService(AttendanceRepository attendanceRepository, UserRepository userRepository) {
        this.attendanceRepository = attendanceRepository;
        this.userRepository = userRepository;
    }

    @Transactional
    public AttendanceDto checkIn(String username, CheckInRequest request) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new ApiException(404, "User not found"));
        LocalDate today = LocalDate.now();
        if (attendanceRepository.findByUserAndAttendanceDate(user, today).isPresent()) {
            throw new ApiException(409, "Already checked in today");
        }
        AttendanceRecord record = new AttendanceRecord();
        record.setUser(user);
        record.setAttendanceDate(today);
        record.setCheckInTime(Instant.now());
        record.setLocation(request.getLocation());
        attendanceRepository.save(record);
        return AttendanceDto.from(record);
    }

    @Transactional
    public AttendanceDto checkOut(String username) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new ApiException(404, "User not found"));
        AttendanceRecord record = attendanceRepository.findByUserAndAttendanceDate(user, LocalDate.now())
                .orElseThrow(() -> new ApiException(404, "No check-in record today"));
        if (record.getCheckOutTime() != null) {
            throw new ApiException(409, "Already checked out today");
        }
        record.setCheckOutTime(Instant.now());
        Duration duration = Duration.between(record.getCheckInTime(), record.getCheckOutTime());
        record.setWorkHours(Math.round(duration.toMinutes() / 60.0 * 100.0) / 100.0);
        attendanceRepository.save(record);
        return AttendanceDto.from(record);
    }

    public List<AttendanceDto> myRecords(String username) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new ApiException(404, "User not found"));
        return attendanceRepository.findAllByUserOrderByAttendanceDateDesc(user)
                .stream().map(AttendanceDto::from).toList();
    }
}
