from django.db import models
from django.db.models import Sum
from django.conf import settings

from doctor.models import *
from doctor.models import Doctor, Technician
from core.models import ExchangeRate
from reservation.models import Reservation
class ExpensePaid(models.Model):
    date = models.DateField()
    description = models.CharField(max_length=255,null=True,blank=True)  # توضیح اینکه هزینه برای چی بوده
    cost_dollar = models.DecimalField(max_digits=10, decimal_places=2,null=True, blank=True)
    cost_dinar = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True)
    currency_type  = models.CharField(
        max_length=20,
        choices=[
            ('dollar', 'dollar'),
            ('dinar', 'dinar'),
        ],
        default='dollar'
    )
    expense_type = models.CharField(
        max_length=20,
        choices=[
            ('doctor', 'doctor'),
            ('technician', 'technician'),
        ],
        default='doctor'
    )
    # لینک‌های اختیاری
    doctor = models.ForeignKey(Doctor, on_delete=models.SET_NULL, null=True, blank=True)
    technician = models.ForeignKey(Technician, on_delete=models.SET_NULL, null=True, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)



    def __str__(self):
        return f"{self.date} | {self.description} | ${self.cost_dollar}"
class ExpenseItem(models.Model):
    date = models.DateField()
    description = models.CharField(max_length=255,null=True,blank=True)  # توضیح اینکه هزینه برای چی بوده
    cost_dollar = models.DecimalField(max_digits=10, decimal_places=2,null=True, blank=True)
    medical_name = models.CharField(max_length=50,null=True,blank=True)
    medical_quantity = models.IntegerField(null=True,blank=True)
    cost_dinar = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True)
    currency_type  = models.CharField(
        max_length=20,
        choices=[
            ('dollar', 'dollar'),
            ('dinar', 'dinar'),
        ],
        default='dollar'
    )
    expense_type = models.CharField(
        max_length=20,
        choices=[
            ('doctor', 'doctor'),
            ('technician', 'technician'),
            ('reservation', 'reservation'),
            ('rent', 'rent'),
            ('payment', 'payment'),
            ('food', 'food'),
            ('equipment', 'equipment'),
            ('marketing', 'marketing'),
            ('advertising', 'advertising'),
            ('loantechnician', 'loantechnician'),
            ('loandoctor', 'loandoctor'),
            ('medicalsell', 'medicalsell'),
            ('other', 'other'),
        ],
        default='other'
    )
    # لینک‌های اختیاری
    doctor = models.ForeignKey(Doctor, on_delete=models.SET_NULL, null=True, blank=True)
    technician = models.ForeignKey(Technician, on_delete=models.SET_NULL, null=True, blank=True)
    reservation = models.ForeignKey(Reservation, on_delete=models.SET_NULL, null=True, blank=True)
    details = models.TextField(blank=True, null=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)



    def __str__(self):
        return f"{self.date} | {self.description} | ${self.cost_dollar}"
class ExpenseChangeLog(models.Model):
    """لاگ تغییرات رزرو"""
    ACTION_TYPES = [
        ('create', 'create'),
        ('update', 'update'),
        ('delete', 'delete'),
        ('status_change', 'status change'),
    ]

    expense_paid = models.ForeignKey(
        'ExpensePaid',
        on_delete=models.CASCADE,
        null=True, 
        blank=True
    )
    expense_item = models.ForeignKey(
        'ExpenseItem',
        on_delete=models.CASCADE,
        null=True, 
        blank=True
    )

    action_type = models.CharField(max_length=20, choices=ACTION_TYPES)

    # داده‌های قبل و بعد از تغییر
    old_data = models.TextField(blank=True, null=True)
    new_data = models.TextField(blank=True, null=True)

    # فیلدهای تغییر یافته
    changed_fields = models.TextField(blank=True, null=True)

    # توضیحات تغییر
    description = models.TextField(blank=True, null=True)
    source_model = models.CharField(
        max_length=50,
        choices=[
            ('ExpensePaid', 'ExpensePaid'),
            ('ExpenseItem', 'ExpenseItem'),
        ],
        default='Reservation'
    )
    # کاربر انجام‌دهنده تغییر
    changed_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="expense_changes"
    )

    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-timestamp']

    def __str__(self):
        user_name = self.changed_by.username if self.changed_by else "N/A"
        return f"{self.get_action_type_display()} - {user_name} - {self.timestamp.strftime('%Y/%m/%d %H:%M')}"


class OtherCost(models.Model):
    description = models.CharField(max_length=255)
    cost_dollar = models.DecimalField(max_digits=10, decimal_places=2)

class Expense(models.Model):
    date = models.DateField()
    doctors = models.ManyToManyField(Doctor, through='ExpenseDoctor')
    technicians = models.ManyToManyField(Technician, through='ExpenseTechnician')
    fixed_cost_dollar = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    other_costs = models.ManyToManyField(OtherCost, through='ExpenseOtherCost')
    # total_dollar = models.DecimalField(max_digits=10, decimal_places=2)

    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)  # Updated field

    @property
    def total_dollar(self):
        doctor_costs = self.expense_doctor.aggregate(total=Sum('cost_dollar'))['total'] or 0
        technician_costs = self.expense_technician.aggregate(total=Sum('cost_dollar'))['total'] or 0
        fixed_cost = self.fixed_cost_dollar or 0
        other_costs = self.expense_other_cost.aggregate(total=Sum('cost_dollar'))['total'] or 0
        return doctor_costs + technician_costs + fixed_cost + other_costs

    def get_doctors_and_costs(self):
        doctors_costs = []
        for expense_doctor in self.expense_doctor.all():
            doctors_costs.append({
                'doctor': expense_doctor.doctor,
                'cost_dollar': expense_doctor.cost_dollar
            })
        return doctors_costs

    def get_technicians_and_costs(self):
        return self.expense_technician.select_related('technician').all()

    def get_other_costs_and_descriptions(self):
        other_costs = []
        for expense_other_cost in self.expense_other_cost.all():
            other_costs.append({
                'cost_dollar': expense_other_cost.cost_dollar,
                'description': expense_other_cost.description,
            })
        return other_costs

class ExpenseDoctor(models.Model):
    expense = models.ForeignKey(Expense, on_delete=models.CASCADE, related_name='expense_doctor')
    doctor = models.ForeignKey(Doctor, on_delete=models.SET_NULL , null=True)
    cost_dollar = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)

class ExpenseTechnician(models.Model):
    expense = models.ForeignKey(Expense, on_delete=models.CASCADE, related_name='expense_technician')
    technician = models.ForeignKey(Technician, on_delete=models.SET_NULL , null=True)
    cost_dollar = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)

class ExpenseOtherCost(models.Model):
    expense = models.ForeignKey(Expense, on_delete=models.CASCADE, related_name='expense_other_cost')
    other_cost = models.ForeignKey(OtherCost, on_delete=models.CASCADE, null=True, blank=True)
    description = models.CharField(max_length=255)
    cost_dollar = models.DecimalField(max_digits=10, decimal_places=2)
