using OmsorgCore.Application.Abstractions;
using OmsorgCore.Domain.Entities;

namespace OmsorgCore.Application.Services;

public class FacilityContactService : IFacilityContactService
{
    private readonly IFacilityContactRepository _facilityContactRepository;

    public FacilityContactService(IFacilityContactRepository facilityContactRepository)
    {
        _facilityContactRepository = facilityContactRepository;
    }

    public Task<IReadOnlyList<FacilityContact>> GetByFacilityIdAsync(Guid facilityId, CancellationToken cancellationToken = default)
        => _facilityContactRepository.GetByFacilityIdAsync(facilityId, cancellationToken);

    public Task<FacilityContact?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
        => _facilityContactRepository.GetByIdAsync(id, cancellationToken);

    public async Task<FacilityContact> CreateAsync(FacilityContact contact, CancellationToken cancellationToken = default)
    {
        await _facilityContactRepository.AddAsync(contact, cancellationToken);
        await _facilityContactRepository.SaveChangesAsync(cancellationToken);
        return contact;
    }

    public async Task<FacilityContact?> UpdateAsync(Guid id, FacilityContact updates, CancellationToken cancellationToken = default)
    {
        var contact = await _facilityContactRepository.GetByIdAsync(id, cancellationToken);
        if (contact is null)
        {
            return null;
        }

        contact.Name = updates.Name;
        contact.Role = updates.Role;
        contact.Department = updates.Department;
        contact.PhoneNumber = updates.PhoneNumber;
        contact.Email = updates.Email;
        contact.Notes = updates.Notes;
        contact.UpdatedAt = DateTime.UtcNow;

        await _facilityContactRepository.UpdateAsync(contact, cancellationToken);
        await _facilityContactRepository.SaveChangesAsync(cancellationToken);
        return contact;
    }

    public async Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken = default)
    {
        var deleted = await _facilityContactRepository.SoftDeleteAsync(id, cancellationToken);
        if (deleted)
        {
            await _facilityContactRepository.SaveChangesAsync(cancellationToken);
        }

        return deleted;
    }

    public Task<IReadOnlyList<FacilityContact>> GetDeletedAsync(string? search, CancellationToken cancellationToken = default)
        => _facilityContactRepository.GetDeletedAsync(search, cancellationToken);

    public async Task<bool> RestoreAsync(Guid id, CancellationToken cancellationToken = default)
    {
        var restored = await _facilityContactRepository.RestoreAsync(id, cancellationToken);
        if (restored)
        {
            await _facilityContactRepository.SaveChangesAsync(cancellationToken);
        }

        return restored;
    }
}
