# Copyright (c) 2024, JINGROW
# See license.txt

from __future__ import annotations

from datetime import date
from unittest.mock import patch

import jingrow
from jingrow.model.naming import make_autoname
from jingrow.tests.utils import JingrowTestCase


def create_test_plan(
	document_type: str,
	price_usd: float = 10.0,
	price_cny: float = 750.0,
	cpu_time: int = 1,
	plan_title: str | None = None,
	plan_name: str | None = None,
	allow_downgrading_from_other_plan: bool = True,
	allowed_apps: list[str] | None = None,
	release_groups: list[str] | None = None,
	private_benches: bool = False,
	is_trial_plan: bool = False,
):
	"""Create test Plan pg."""
	plan_name = plan_name or f"Test {document_type} plan {make_autoname('.#')}"
	plan_title = plan_name
	plan = jingrow.get_pg(
		{
			"pagetype": "Site Plan",
			"document_type": "Site",
			"name": plan_name,
			"plan_title": plan_title,
			"price_cny": price_cny,
			"price_usd": price_usd,
			"cpu_time_per_day": cpu_time,
			"allow_downgrading_from_other_plan": allow_downgrading_from_other_plan,
			"disk": 50,
			"instance_type": "t2.micro",
			"private_benches": private_benches,
			"is_trial_plan": is_trial_plan,
		}
	)
	if allowed_apps:
		for app in allowed_apps:
			plan.append("allowed_apps", {"app": app})
	if release_groups:
		for release_group in release_groups:
			plan.append("release_groups", {"release_group": release_group})

	plan.insert(ignore_if_duplicate=True)
	plan.reload()
	return plan


class TestSitePlan(JingrowTestCase):
	def setUp(self):
		self.plan = create_test_plan("Site")

	def tearDown(self):
		jingrow.db.rollback()

	def test_period_int(self):
		self.assertIsInstance(self.plan.period, int)

	def test_per_day_difference(self):
		per_day_usd = self.plan.get_price_per_day("USD")
		per_day_cny = self.plan.get_price_per_day("CNY")
		self.assertIsInstance(per_day_cny, (int, float))
		self.assertIsInstance(per_day_usd, (int, float))
		self.assertNotEqual(per_day_cny, per_day_usd)

	def test_dynamic_period(self):
		month_with_29_days = jingrow.utils.get_last_day(date(2020, 2, 3))
		month_with_30_days = jingrow.utils.get_last_day(date(1997, 4, 3))

		with patch.object(jingrow.utils, "get_last_day", return_value=month_with_30_days):
			self.assertEqual(self.plan.period, 30)
			per_day_for_30_usd = self.plan.get_price_per_day("USD")
			per_day_for_30_cny = self.plan.get_price_per_day("CNY")

		with patch.object(jingrow.utils, "get_last_day", return_value=month_with_29_days):
			self.assertEqual(self.plan.period, 29)
			per_day_for_29_usd = self.plan.get_price_per_day("USD")
			per_day_for_29_cny = self.plan.get_price_per_day("CNY")

		self.assertNotEqual(per_day_for_29_usd, per_day_for_30_usd)
		self.assertNotEqual(per_day_for_29_cny, per_day_for_30_cny)
