# 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/>.

import uuid
from datetime import datetime

import pytest

from eo_gestion.eo_facture.models import Client, Contrat


@pytest.mark.parametrize(
    'periodicite, debut, fin, nombre_d_echeances, echeances',
    [
        ('annuelle', '2022-08-31', '2022-08-31', 0, []),
        ('annuelle', '2022-08-31', '2022-09-01', 1, [(1, '2022-08-31', '2023-08-31')]),
        ('annuelle', '2022-08-31', '2023-08-31', 1, [(1, '2022-08-31', '2023-08-31')]),
        (
            'annuelle',
            '2022-08-31',
            '2023-09-01',
            2,
            [(1, '2022-08-31', '2023-08-31'), (2, '2023-08-31', '2024-08-31')],
        ),
        (
            'annuelle',
            '%s-08-31' % (datetime.now().year + 1),
            None,
            1,
            [
                (x, '%s-08-31' % (datetime.now().year + x), '%s-08-31' % (datetime.now().year + x + 1))
                for x in range(1, 4)
            ],
        ),
    ],
)
def test_periodicite_echeances(periodicite, debut, fin, echeances, nombre_d_echeances, db, django_user_model):
    client = Client.objects.create(nom=str(uuid.uuid4()))
    user = django_user_model.objects.all()[0]
    contrat = Contrat.objects.create(
        client=client,
        creator=user,
        intitule=str(uuid.uuid4()),
        periodicite=periodicite,
        periodicite_debut=datetime.strptime(debut, '%Y-%m-%d').date(),
        periodicite_fin=datetime.strptime(fin, '%Y-%m-%d').date() if fin else None,
    )

    assert [
        (x, y.strftime('%Y-%m-%d'), z.strftime('%Y-%m-%d')) for x, y, z in contrat.periodicite_echeances()
    ] == echeances
    assert contrat.periodicite_nombre_d_echeances() == nombre_d_echeances
