from django.db import models
#from phonenumber_field.modelfields import PhoneNumberField
from django.core.validators import RegexValidator
from phonenumbers import parse, is_valid_number, format_number, PhoneNumberFormat
from phonenumbers.phonenumberutil import NumberParseException
from django.utils.translation import gettext_lazy as _

# Create your models here.
class Employee(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    phone_number = models.CharField(max_length=15, unique=True)
    email = models.EmailField(max_length=100)
    position = models.CharField(max_length=20)
    address = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def clean(self):
        """Custom validation to ensure the phone number is in international format."""
        if not self.phone_number:
            return  # Skip validation if phone number is empty
        try:
             # Ensure the number includes country code
            if not self.phone_number.startswith('+'):
                self.phone_number = '+62' + self.phone_number.lstrip('0')
                
            parsed_phone = parse(self.phone_number, "ID")  # Default region: Indonesia
            if not is_valid_number(parsed_phone):
                raise ValueError("Invalid phone number")
            # Save phone number in E.164 format (e.g., +62813xxxx)
            self.phone_number = format_number(parsed_phone, PhoneNumberFormat.E164)
        except NumberParseException:
            raise ValueError("Invalid phone number format")

    def __str__(self):
        return self.name
    
    class Meta:
        managed = False  # Jangan biarkan Django mengelola tabel ini
        db_table = 'employees'  # Nama tabel di database
        verbose_name = "Employee"  # Nama tunggal
        verbose_name_plural = "Employees"  # Nama jamak

class Supplier(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100, verbose_name="Perusahaan")
    contact_person = models.CharField(max_length=100)
    phone_number = models.CharField(max_length=15, unique=True)
    email = models.EmailField(max_length=100)
    address = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def clean(self):
        """Custom validation to ensure the phone number is in international format."""
        if not self.phone_number:
            return
        try:
            if not self.phone_number.startswith('+'):
                self.phone_number = '+62' + self.phone_number.lstrip('0')
                
            parsed_phone = parse(self.phone_number, "ID")
            if not is_valid_number(parsed_phone):
                raise ValueError("Invalid phone number")
            self.phone_number = format_number(parsed_phone, PhoneNumberFormat.E164)
        except NumberParseException:
            raise ValueError("Invalid phone number format")
        
    def __str__(self):
        return self.name
    
    class Meta:
        managed = False 
        db_table = 'suppliers' 
        verbose_name = "Supplier" 
        verbose_name_plural = "Suppliers" 

class Customer(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    phone_number = models.CharField(max_length=15, unique=True)
    email = models.EmailField(max_length=100)
    address = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def clean(self):
        """Custom validation to ensure the phone number is in international format."""
        if not self.phone_number:
            return
        try:             
            if not self.phone_number.startswith('+'):
                self.phone_number = '+62' + self.phone_number.lstrip('0')
                
            parsed_phone = parse(self.phone_number, "ID")
            if not is_valid_number(parsed_phone):
                raise ValueError("Invalid phone number")            
            self.phone_number = format_number(parsed_phone, PhoneNumberFormat.E164)
        except NumberParseException:
            raise ValueError("Invalid phone number format")

    def __str__(self):
        return self.name
    
    class Meta:
        managed = False
        db_table = 'customers'
        verbose_name = "Customer" 
        verbose_name_plural = "Customers"