# barbacompta - invoicing for dummies
# Copyright (C) 2019-2022 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from decimal import Decimal

import pytest
from django.contrib.auth import get_user_model

from eo_gestion.eo_facture.models import Client, Contrat, Facture, Ligne, Prestation


@pytest.fixture
def user(db):
    User = get_user_model()
    return User.objects.get(username='admin')


@pytest.fixture
def client(db):
    return Client.objects.create(
        nom='Mairie de clapotis-les-canards',
        adresse='''26 Rue de la Grand Marre
17310 Saint-Pierre-d'Oléron
Charente-Maritime - Poitou-Charentes - France''',
        tva=Decimal('20.01'),
    )


@pytest.fixture
def contrat(user, client):
    contrat = Contrat.objects.create(
        client=client,
        intitule='Entretient de la marre',
        tva=Decimal('20.02'),
        creator=user,
    )
    Prestation.objects.create(
        contrat=contrat,
        intitule='Faucardage',
        prix_unitaire_ht=1000,
        quantite=2,
    )
    return contrat


@pytest.fixture
def facture(contrat, client, user):
    facture = Facture.objects.create(
        client=client,
        intitule='Entretient marre',
        contrat=contrat,
        taux_tva=Decimal('20.03'),
        creator=user,
    )
    Ligne.objects.create(
        facture=facture,
        intitule='Faucardage',
        prix_unitaire_ht='1000',
        quantite=1,
        taux_tva=Decimal('20.04'),
    )
    return facture


def test_facture_tva(facture):
    assert facture.client.tva == Decimal('20.01')
    assert facture.contrat.tva == Decimal('20.02')
    assert facture.taux_tva == Decimal('20.03')
    assert facture.lignes.first().taux_tva == Decimal('20.04')

    assert facture.tva == Decimal('200.40')

    ligne = facture.lignes.first()
    ligne.taux_tva = 0
    ligne.save()
    assert facture.tva == Decimal('0.00')

    ligne.taux_tva = None
    ligne.save()
    assert facture.tva == Decimal('200.30')

    facture.taux_tva = 0
    facture.save()
    assert facture.tva == Decimal('0.00')

    facture.taux_tva = None
    facture.save()
    assert facture.tva == Decimal('200.20')

    facture.contrat.tva = 0
    facture.save()
    assert facture.tva == Decimal('0.00')

    facture.contrat.tva = None
    facture.save()
    assert facture.tva == Decimal('200.10')
