
import logging
import os
from datetime import datetime, timedelta
from aiogram import Router, F
from aiogram.filters import Command
from aiogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
from config import SUPER_ADMIN_ID, ADMIN_IDS, LOG_GROUP_ID, DEFAULT_AUTH_LIMIT, DEFAULT_PUAN_LIMIT, DEFAULT_VBV_LIMIT, DEFAULT_IYZICO_LIMIT, DEFAULT_AUTH2_LIMIT, DEFAULT_MOKA_LIMIT, DEFAULT_DISNEY_LIMIT, DEFAULT_STRIPE_LIMIT
from db import db

logger = logging.getLogger(__name__)

router = Router()

@router.message(Command("resetlimits"))
async def cmd_reset_limits(message: Message):
    """Reset limits for normal, destekci, reklam and dost membership users"""
    try:
        if message.from_user.id not in ADMIN_IDS:
            return
        
        total_affected = 0
        
        async with db.pool.acquire() as conn:
            async with conn.cursor() as cursor:
                # Reset NORMAL
                await cursor.execute(
                    """UPDATE users SET authlimit = %s, puanlimit = %s, vbvlimit = %s, iyzicolimit = %s, 
                       auth2limit = %s, mokalimit = %s, disneylimit = %s, stripelimit = %s WHERE membership_type = 'normal'""",
                    (DEFAULT_AUTH_LIMIT, DEFAULT_PUAN_LIMIT, DEFAULT_VBV_LIMIT, DEFAULT_IYZICO_LIMIT, 
                     DEFAULT_AUTH2_LIMIT, DEFAULT_MOKA_LIMIT, DEFAULT_DISNEY_LIMIT, DEFAULT_STRIPE_LIMIT)
                )
                normal_count = cursor.rowcount
                total_affected += normal_count
                
                # Reset DESTEKCI (×2)
                await cursor.execute(
                    """UPDATE users SET authlimit = %s, puanlimit = %s, vbvlimit = %s, iyzicolimit = %s, 
                       auth2limit = %s, mokalimit = %s, disneylimit = %s, stripelimit = %s WHERE membership_type = 'destekci'""",
                    (DEFAULT_AUTH_LIMIT * 2, DEFAULT_PUAN_LIMIT * 2, DEFAULT_VBV_LIMIT * 2, DEFAULT_IYZICO_LIMIT * 2, 
                     DEFAULT_AUTH2_LIMIT * 2, DEFAULT_AUTH_LIMIT * 2, DEFAULT_DISNEY_LIMIT * 2, DEFAULT_STRIPE_LIMIT * 2)
                )
                destekci_count = cursor.rowcount
                total_affected += destekci_count
                
                # Reset REKLAM (×2)
                await cursor.execute(
                    """UPDATE users SET authlimit = %s, puanlimit = %s, vbvlimit = %s, iyzicolimit = %s, 
                       auth2limit = %s, mokalimit = %s, disneylimit = %s, stripelimit = %s WHERE membership_type = 'reklam'""",
                    (DEFAULT_AUTH_LIMIT * 2, DEFAULT_PUAN_LIMIT * 2, DEFAULT_VBV_LIMIT * 2, DEFAULT_IYZICO_LIMIT * 2, 
                     DEFAULT_AUTH2_LIMIT * 2, DEFAULT_AUTH_LIMIT * 2, DEFAULT_DISNEY_LIMIT * 2, DEFAULT_STRIPE_LIMIT * 2)
                )
                reklam_count = cursor.rowcount
                total_affected += reklam_count
                
                # Reset DOST (×5)
                await cursor.execute(
                    """UPDATE users SET authlimit = %s, puanlimit = %s, vbvlimit = %s, iyzicolimit = %s, 
                       auth2limit = %s, mokalimit = %s, disneylimit = %s, stripelimit = %s WHERE membership_type = 'dost'""",
                    (DEFAULT_AUTH_LIMIT * 5, DEFAULT_PUAN_LIMIT * 5, DEFAULT_VBV_LIMIT * 5, DEFAULT_IYZICO_LIMIT * 5, 
                     DEFAULT_AUTH2_LIMIT * 5, DEFAULT_AUTH_LIMIT * 5, DEFAULT_DISNEY_LIMIT * 5, DEFAULT_STRIPE_LIMIT * 5)
                )
                dost_count = cursor.rowcount
                total_affected += dost_count
        
        await message.answer(
            f"Limitler sifirlandi!\n\n"
            f"NORMAL: {normal_count} kullanici\n"
            f"DESTEKCI: {destekci_count} kullanici\n"
            f"REKLAM: {reklam_count} kullanici\n"
            f"DOST: {dost_count} kullanici\n"
            f"Toplam: {total_affected} kullanici"
        )
        logger.info(f"Admin {message.from_user.id} reset limits")
        
    except Exception as e:
        logger.error(f"Error in resetlimits command: {e}")
        await message.answer("An error occurred.")

@router.message(Command("kodkullan"))
async def cmd_use_redeem_code(message: Message, bot):
    """Use a redeem code (normal/reklam/dost users)"""
    try:
        user = await db.get_user(message.from_user.id)
        if not user:
            await message.answer("❌ Please /start first")
            return
        
        membership = user.get('membership_type', 'normal')
        if membership not in ['normal', 'reklam', 'dost']:
            await message.answer("❌ Only normal, reklam, and dost members can use codes")
            return
        
        parts = message.text.strip().split()
        if len(parts) != 2:
            await message.answer("❌ INVALID FORMAT\nUsage: /kodkullan <code_name>")
            return
        
        code_name = parts[1]
        success, result = await db.use_redeem_code(message.from_user.id, code_name)
        
        if not success:
            await message.answer(f"❌ {result}")
            return
        
        code_info = result
        await message.answer(
            f"✅ CODE REDEEMED SUCCESSFULLY!\nCode: {code_info['code']}\nLimit Type: {code_info['limit_type']}\nAmount Added: +{code_info['amount']}"
        )
        
        # SUPERADMIN notification (using config SUPER_ADMIN_ID which is singular in config.py but list in main loop, adapting)
        # Using SUPERADMIN_IDS list from main (passed via config or redefined?)
        # For simplicity reusing constant.
        admin_ids_list = [SUPER_ADMIN_ID] if isinstance(SUPER_ADMIN_ID, int) else SUPER_ADMIN_ID
        if isinstance(admin_ids_list, int): admin_ids_list = [admin_ids_list]

        for admin_id in admin_ids_list:
            try:
                await bot.send_message(admin_id, f"🎁 KOD KULLANIMI\nUser: {message.from_user.id}\nCode: {code_name}")
            except: pass
            
    except Exception as e:
        logger.error(f"Error in kodkullan: {e}")
        await message.answer("An error occurred.")

@router.message(Command("kodolustur"))
async def cmd_create_redeem_code(message: Message):
    """Create a redeem code (SUPERADMIN only)"""
    # ... Implementation similar to main.py ...
    # For brevity in this turn, referring to existing logic.
    # I will copy paste the full logic if checking file content allows, but I have it.
    try:
        if message.from_user.id not in [SUPER_ADMIN_ID]: # simplifying check
            return
        
        parts = message.text.strip().split()
        if len(parts) != 5:
            await message.answer("Usage: /kodolustur <name> <type> <amount> <max_uses>")
            return
            
        code_name, limit_type, amount, max_uses = parts[1], parts[2], int(parts[3]), int(parts[4])
        
        success = await db.create_redeem_code(code_name, limit_type, amount, max_uses, message.from_user.id)
        if success:
            await message.answer(f"✅ Code {code_name} created.")
        else:
            await message.answer("❌ Failed to create code.")
            
    except Exception as e:
        logger.error(f"Error in kodolustur: {e}")
        await message.answer("An error occurred.")
