using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Application.Aggregates.Stores.ViewModels;
using Domain.Aggregates.Stores;
using Domain.Aggregates.Stores.Data;
using Mapster;
using Resources.Messages;

namespace Application.Aggregates.Stores;

public class StoresApplication(IStoreRepository storeRepository)
{
    public async Task<StoreViewModel> CreateAsync(CreateStoreViewModel storeViewModel)
    {
        var store = Store.Create(
            name: storeViewModel.Name,
            address: storeViewModel.Address,
            mobile: storeViewModel.Mobile,
            score: storeViewModel.Score);

        if (storeViewModel.IsActive == true)
        {
            store.Activate();
        }

        await storeRepository.AddAsync(store);
        await storeRepository.SaveChangesAsync();

        return store.Adapt<StoreViewModel>();
    }

    public async Task<List<StoreViewModel>> GetStors()
    {
        var store =
            await storeRepository.GetAllAsync();

        return store.Adapt<List<StoreViewModel>>();
    }

    public async Task<StoreViewModel> GetAsync(Guid storeId)
    {
        var store =
            await storeRepository.GetAsync(storeId);

        return store.Adapt<StoreViewModel>();
    }

    public async Task<StoreViewModel> UpdateAsync(UpdateStoreViewModel updateStoreViewModel)
    {
        var update =
            await storeRepository.GetAsync(updateStoreViewModel.Id);

        if (update == null || updateStoreViewModel.Id == Guid.Empty)
        {
            var error =
                string.Format(Errors.NotFound, Resources.DataDictionary.Store);

            throw new Exception(error);
        }

        update.Update(
            name: updateStoreViewModel.Name,
            address: updateStoreViewModel.Address,
            mobile: updateStoreViewModel.Mobile,
            score: updateStoreViewModel.Score);

        if (update.IsActive == true)
        {
            update.Activate();
        }
        else
        {
            update.Deactivate();
        }

        await storeRepository.SaveChangesAsync();

        return update.Adapt<StoreViewModel>();
    }

    public async Task DeleteAsync(Guid storeId)
    {
        var delete =
            await storeRepository.GetAsync(storeId);

        if (delete == null || delete.Id == Guid.Empty)
        {
            var error =
                string.Format(Errors.NotFound, Resources.DataDictionary.Store);

            throw new Exception(error);
        }

        storeRepository.Remove(delete);

        await storeRepository.SaveChangesAsync();
    }
}
