from rest_framework import serializers

from apps.billing.models import CreditAccount

from .models import Team, TeamMember, User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id", "username", "first_name", "last_name", "email", "phone", "avatar_url", "status"]
        read_only_fields = ["id", "status"]


class TeamSerializer(serializers.ModelSerializer):
    class Meta:
        model = Team
        fields = ["id", "name", "status", "owner", "created_at", "updated_at"]
        read_only_fields = ["id", "status", "owner", "created_at", "updated_at"]


class TeamMemberSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = TeamMember
        fields = ["id", "team", "user", "role", "status", "monthly_credit_limit"]
        read_only_fields = ["id", "team", "user", "status"]


class RegisterSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=150)
    password = serializers.CharField(min_length=8, write_only=True)
    email = serializers.EmailField(required=False, allow_blank=True)
    team_name = serializers.CharField(max_length=128, required=False, allow_blank=True)

    def validate_username(self, value):
        if User.objects.filter(username=value).exists():
            raise serializers.ValidationError("username already exists")
        return value

    def create(self, validated_data):
        from decimal import Decimal

        from django.conf import settings
        from django.db import transaction

        with transaction.atomic():
            user = User.objects.create_user(
                username=validated_data["username"],
                password=validated_data["password"],
                email=validated_data.get("email", ""),
            )
            team = Team.objects.create(
                name=validated_data.get("team_name") or f"{user.username}'s Team",
                owner=user,
            )
            TeamMember.objects.create(team=team, user=user, role=TeamMember.Role.OWNER)
            CreditAccount.objects.create(
                team=team,
                balance=Decimal(str(settings.DEFAULT_TRIAL_CREDITS)),
            )
        return {"user": user, "team": team}


class LoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField(write_only=True)
