using AutoMapper;
using Entities.Contracts;
using Entities.DTO;
using Microsoft.AspNetCore.Identity;
using SharedDATA.Api;
using System.Net;

namespace TechHelper.Services
{
	public class NoteService : INoteService
	{
		private readonly IUnitOfWork _work;
		private readonly IMapper _mapper;

		public NoteService(IUnitOfWork work)
		{
			_work = work;
		}

		public async Task<ApiResponse> AddAsync(GlobalDto model)
		{
			try
			{
				var globalEntity = new Global
				{
					Area = model.SubjectArea,
					Info = model.Data
				};

				await _work.GetRepository<Global>().InsertAsync(globalEntity);
				await _work.SaveChangesAsync();

				return ApiResponse.Success("数据已成功添加。");
			}
			catch (Exception ex)
			{
				return ApiResponse.Error($"添加数据时发生错误: {ex.Message}");
			}
		}

		public async Task<ApiResponse> DeleteAsync(byte id)
		{
			var globalRepo = _work.GetRepository<Global>();
			var globalEntity = await globalRepo.GetFirstOrDefaultAsync(predicate: x => x.Area == (SubjectAreaEnum)id);

			if (globalEntity == null)
			{
				return ApiResponse.Error("未找到要删除的数据。");
			}

			globalRepo.Delete(globalEntity);
			await _work.SaveChangesAsync();

			return ApiResponse.Success("数据已成功删除。");
		}

		public async Task<ApiResponse> GetAllAsync(QueryParameter query)
		{
			var repository = _work.GetRepository<Global>();
			// 获取所有实体，并将其 Info 属性作为结果返回
			var entities = await repository.GetAllAsync();

			// 直接返回字符串列表
			var resultData = entities.Select(e => e.Info).ToList();

			return ApiResponse.Success("数据已成功检索。", resultData);
		}

		public async Task<ApiResponse> GetAsync(byte id)
		{
			var globalEntity = await _work.GetRepository<Global>().GetFirstOrDefaultAsync(predicate: x => x.Area == (SubjectAreaEnum)id);

			if (globalEntity == null)
			{
				return ApiResponse.Error("未找到数据。");
			}

			// 直接返回 Info 字符串
			return ApiResponse.Success("数据已成功检索。", globalEntity.Info);
		}

		public async Task<ApiResponse> UpdateAsync(GlobalDto model)
		{
			try
			{
				var repository = _work.GetRepository<Global>();
				var existingEntity = await repository.GetFirstOrDefaultAsync(predicate: x => x.Area == (SubjectAreaEnum)model.SubjectArea);

				if (existingEntity == null)
				{
					return ApiResponse.Error("未找到要更新的数据。");
				}

				// 直接将传入的字符串赋值给 Info 属性
				existingEntity.Info = model.Data;
				repository.Update(existingEntity);
				await _work.SaveChangesAsync();

				return ApiResponse.Success("数据已成功更新。");
			}
			catch (Exception ex)
			{
				return ApiResponse.Error($"更新数据时发生错误: {ex.Message}");
			}
		}
	}
}
