using AutoMapper;
using SportsDivision.Application.DTOs;
using SportsDivision.Application.Interfaces;
using SportsDivision.Domain.Entities;
using SportsDivision.Domain.Enums;
using SportsDivision.Domain.Interfaces;

namespace SportsDivision.Application.Services;

public class SchoolService : ISchoolService
{
    private readonly IUnitOfWork _uow;
    private readonly IMapper _mapper;

    public SchoolService(IUnitOfWork uow, IMapper mapper)
    {
        _uow = uow;
        _mapper = mapper;
    }

    public async Task<IEnumerable<SchoolDto>> GetAllAsync()
    {
        var schools = await _uow.Schools.GetAllAsync();
        return _mapper.Map<IEnumerable<SchoolDto>>(schools);
    }

    public async Task<SchoolDto?> GetByIdAsync(int id)
    {
        var school = await _uow.Schools.GetWithStudentsAsync(id);
        return school == null ? null : _mapper.Map<SchoolDto>(school);
    }

    public async Task<IEnumerable<SchoolDto>> GetByZoneAsync(int zoneId)
    {
        var schools = await _uow.Schools.GetByZoneAsync(zoneId);
        return _mapper.Map<IEnumerable<SchoolDto>>(schools);
    }

    public async Task<IEnumerable<SchoolDto>> GetBySchoolLevelAsync(SchoolLevel level)
    {
        var schools = await _uow.Schools.GetBySchoolLevelAsync(level);
        return _mapper.Map<IEnumerable<SchoolDto>>(schools);
    }

    public async Task<SchoolDto> CreateAsync(SchoolCreateDto dto)
    {
        var school = _mapper.Map<School>(dto);
        await _uow.Schools.AddAsync(school);
        await _uow.SaveChangesAsync();
        return _mapper.Map<SchoolDto>(school);
    }

    public async Task UpdateAsync(SchoolUpdateDto dto)
    {
        var school = await _uow.Schools.GetByIdAsync(dto.SchoolId)
            ?? throw new KeyNotFoundException("School not found.");
        _mapper.Map(dto, school);
        _uow.Schools.Update(school);
        await _uow.SaveChangesAsync();
    }

    public async Task DeleteAsync(int id)
    {
        var school = await _uow.Schools.GetByIdAsync(id)
            ?? throw new KeyNotFoundException("School not found.");
        _uow.Schools.Remove(school);
        await _uow.SaveChangesAsync();
    }
}
