using Minesweeper.Config;
using Minesweeper.Core;
using Minesweeper.Presentation.Views;
using UnityEngine;

namespace Minesweeper.Presentation.Factories
{
    public sealed class CellViewFactory : ICellViewFactory
    {
        private readonly MinesweeperUiConfig uiConfig;

        public CellViewFactory(MinesweeperUiConfig uiConfig)
        {
            this.uiConfig = uiConfig;
        }

        public CellView CreateCell(BoardCellData cell, Transform parent)
        {
            var prefab = uiConfig.CellButtonPrefab;
            if (prefab == null)
            {
                Debug.LogError("CellViewFactory failed: CellButtonPrefab is not assigned.");
                return null;
            }

            var go = Object.Instantiate(prefab, parent);
            go.name = BuildCellName(cell.X, cell.Y, cell.DisplayValue);

            var view = go.GetComponent<CellView>();
            if (view == null)
            {
                Debug.LogError($"CellViewFactory failed: '{prefab.name}' is missing CellView.");
                Object.Destroy(go);
                return null;
            }

            view.Initialize(cell.X, cell.Y);
            return view;
        }

        public string BuildCellName(int x, int y, int value, bool isMine)
        {
            return $"bt_{x}_{y}_{(isMine ? "M" : value.ToString())}";
        }

        public string BuildCellName(int x, int y, string displayValue)
        {
            return $"bt_{x}_{y}_{displayValue}";
        }

    }
}
