using Marco.Pms.DataAccess.Data;
using Marco.Pms.Model.Dtos.Util;
using Marco.Pms.Model.Mapper;
using Marco.Pms.Model.Master;
using Marco.Pms.Model.Utilities;
using MarcoBMS.Services.Helpers;
using MarcoBMS.Services.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Marco.Pms.Services.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MarketController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly UserHelper _userHelper;
        private readonly IEmailSender _emailSender;
        private readonly IConfiguration _configuration;
        public MarketController(ApplicationDbContext context, UserHelper userHelper, RefreshTokenService refreshTokenService,
            IEmailSender emailSender, IConfiguration configuration, EmployeeHelper employeeHelper)
        {
            _context = context;
            _userHelper = userHelper;
            _emailSender = emailSender;
            _configuration = configuration;
        }

        [HttpGet]
        [Route("industries")]
        public async Task<IActionResult> GetIndustries()
        {
            var tenantId = _userHelper.GetTenantId();
            var industries = await _context.Industries.ToListAsync();

            return Ok(ApiResponse<object>.SuccessResponse(industries, "Success.", 200));
        }

        [HttpPost("enquire")]
        public async Task<IActionResult> RequestDemo([FromBody] InquiryDto inquiryDto)
        {
            Inquiries inquiry = inquiryDto.ToInquiriesFromInquiriesDto();
            _context.Inquiries.Add(inquiry);
            await _context.SaveChangesAsync();

            Industry industry = await _context.Industries.FirstOrDefaultAsync(i => i.Id == inquiryDto.IndustryId) ?? new Industry();
            if (industry != null && industry.Name != null)
            {
                InquiryEmailObject inquiryEmailObject = inquiryDto.ToInquiryEmailObjectFromInquiriesDto(industry.Name);
                string emails = _configuration["MailingList:RequestDemoReceivers"] ?? "";
                List<string> result = emails
                    .Split(';', StringSplitOptions.RemoveEmptyEntries)
                    .Select(item => item.Trim())
                    .ToList();
                await _emailSender.SendRequestDemoEmail(result, inquiryEmailObject);
                return Ok(ApiResponse<object>.SuccessResponse(new { }, "Email sent.", 200));
            }
            return NotFound(ApiResponse<object>.ErrorResponse("Industry not found.", "Industry not found.", 404));
        }
    }
}
