"""
Name change handler
Supports:
- First name only
- Full name
"""

from remottxrea.actions.change_name import NameChanger


class ChangeNameHandler:

    def __init__(self, runner):
        self.runner = runner

    # ---------------------------------
    async def handle(self, message):

        if not message or not message.text:
            return

        text = message.text.strip()
        text_lower = text.lower()

        # =========================================
        # FIRST NAME ONLY
        # Command:
        # changeFname Alex
        # =========================================
        if text_lower.startswith("changefname"):

            parts = text.split(" ", 1)

            if len(parts) < 2:
                return await message.reply_text(
                    "Usage:\nchangeFname Alex"
                )

            first_name = parts[1].strip()

            if not first_name:
                return await message.reply_text(
                    "First name cannot be empty"
                )

            # ---------- ACTION ----------
            async def action(phone, app):

                try:
                    changer = NameChanger(app, phone)

                    await changer.change(
                        first_name=first_name,
                        last_name=None
                    )

                    return f"{phone} → First name updated"

                except Exception as e:
                    return f"{phone} → Error: {e}"

            await self.runner.run_action(action)

            return await message.reply_text(
                f"✅ First name changed → {first_name}"
            )

        # =========================================
        # FULL NAME
        # Command:
        # changeName Alex Morgan
        # =========================================
        if text_lower.startswith("changename"):

            parts = text.split(" ", 2)

            if len(parts) < 3:
                return await message.reply_text(
                    "Usage:\nchangeName Alex Morgan"
                )

            first_name = parts[1].strip()
            last_name = parts[2].strip()

            if not first_name or not last_name:
                return await message.reply_text(
                    "First/Last name cannot be empty"
                )

            # ---------- ACTION ----------
            async def action(phone, app):

                try:
                    changer = NameChanger(app, phone)

                    await changer.change(
                        first_name=first_name,
                        last_name=last_name
                    )

                    return f"{phone} → Full name updated"

                except Exception as e:
                    return f"{phone} → Error: {e}"

            await self.runner.run_action(action)

            return await message.reply_text(
                f"✅ Full name updated → {first_name} {last_name}"
            )
