using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Data.Entities;
using Indotalent.Data.Enums;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Infrastructure.Database.Demo;

public static class TransferInSeeder
{
    public static async Task GenerateDataAsync(AppDbContext context)
    {
        if (await context.TransferIn.AnyAsync()) return;

        var random = new Random();
        var transferStatusValues = Enum.GetValues(typeof(TransferStatus)).Cast<TransferStatus>().ToList();
        var entityName = nameof(TransferIn);
        var transferOutEntityName = nameof(TransferOut);
        var ivtEntityName = nameof(InventoryTransaction);

        var transferOuts = await context.TransferOut
            .Where(x => x.Status >= TransferStatus.Confirmed)
            .ToListAsync();

        foreach (var transferOut in transferOuts)
        {
            bool skip = random.Next(2) == 0;
            if (skip) continue;

            var autoNo = await context.GenerateAutoNumberAsync(
                entityName: entityName,
                prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/"
            );

            var transferIn = new TransferIn
            {
                AutoNumber = autoNo,
                TransferReceiveDate = transferOut.TransferReleaseDate?.AddDays(random.Next(1, 5)),
                Status = transferStatusValues[random.Next(transferStatusValues.Count)],
                TransferOutId = transferOut.Id,
            };
            await context.TransferIn.AddAsync(transferIn);

            var items = await context.InventoryTransaction
                .Where(x => x.ModuleId == transferOut.Id && x.ModuleName == transferOutEntityName)
                .ToListAsync();

            foreach (var item in items)
            {
                var autoNoIVT = await context.GenerateAutoNumberAsync(
                    entityName: ivtEntityName,
                    prefixTemplate: $"{ivtEntityName.ToShortNameConsonant(3)}/{{Year}}/"
                );

                var inventoryTransaction = new InventoryTransaction
                {
                    ModuleId = transferIn.Id,
                    ModuleName = entityName,
                    ModuleCode = "TO-IN",
                    ModuleNumber = transferIn.AutoNumber,
                    MovementDate = transferIn.TransferReceiveDate!.Value,
                    Status = (InventoryTransactionStatus)transferIn.Status,
                    AutoNumber = autoNoIVT,
                    WarehouseId = transferOut.WarehouseToId,
                    ProductId = item.ProductId,
                    Movement = item.Movement
                };

                context.CalculateInvenTrans(inventoryTransaction);
                await context.InventoryTransaction.AddAsync(inventoryTransaction);
            }

            await context.SaveChangesAsync();
        }
    }
}