"""
Comprehensive Test Suite for Multi-Template Certificate Management.
Tests cover:
- Admin authorization for certificate management interfaces.
- Certificate generation with all 6 selectable visual templates.
- Persistent database storage, unique certificate numbers, and audit logging.
- Standalone print-friendly document rendering.
- Public QR verification portal integration.
- Certificate revocation and deletion workflows.
All code contains proper English comments for clarity and maintenance.
"""

import unittest
from datetime import timedelta
from werkzeug.security import generate_password_hash

from app import create_app
from app.extensions import db
from app.models.certificate import IssuedCertificate
from app.models.role import Role
from app.models.user import User


class CertificateTestConfig:
    """Test configuration utilizing in-memory SQLite database for rapid, isolated execution."""
    SECRET_KEY = 'a-super-secret-test-key-with-at-least-32-characters-length'
    SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    WTF_CSRF_ENABLED = False
    TESTING = True
    JWT_ACCESS_TOKEN_EXPIRES = timedelta(minutes=60)
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SAMESITE = 'Lax'
    PERMANENT_SESSION_LIFETIME = timedelta(minutes=60)


class CertificateManagementTests(unittest.TestCase):
    """Unit and Integration tests for Multi-Template Certificate Generation."""

    def setUp(self):
        """Initializes application context, database tables, and authorized user accounts."""
        self.app = create_app(CertificateTestConfig)
        self.context = self.app.app_context()
        self.context.push()
        self.client = self.app.test_client()

        # Build schema
        db.create_all()

        # Seed roles
        self.admin_role = Role(role_name='Admin')
        self.volunteer_role = Role(role_name='Volunteer')
        db.session.add_all([self.admin_role, self.volunteer_role])
        db.session.commit()

        # Seed admin user
        self.admin_user = User(
            full_name='Super Admin',
            email='admin@test.org',
            password_hash=generate_password_hash('admin_pass_123'),
            status='active',
            role_id=self.admin_role.id,
        )
        # Seed volunteer user
        self.volunteer_user = User(
            full_name='Aarav Sharma',
            email='volunteer@test.org',
            password_hash=generate_password_hash('vol_pass_123'),
            status='active',
            role_id=self.volunteer_role.id,
        )
        db.session.add_all([self.admin_user, self.volunteer_user])
        db.session.commit()

    def tearDown(self):
        """Tears down database session and removes all in-memory tables."""
        db.session.remove()
        db.drop_all()
        self.context.pop()

    def _login_as_admin(self):
        """Helper to authenticate test client session as Super Admin."""
        with self.client.session_transaction() as sess:
            sess['_user_id'] = str(self.admin_user.id)
            sess['_fresh'] = True

    def _login_as_volunteer(self):
        """Helper to authenticate test client session as Volunteer."""
        with self.client.session_transaction() as sess:
            sess['_user_id'] = str(self.volunteer_user.id)
            sess['_fresh'] = True

    def test_unauthenticated_access_is_blocked(self):
        """Verifies that unauthenticated requests to the certificate management page are redirected or denied."""
        response = self.client.get('/admin/certificates/user-certificate')
        # Expect redirect to login (302) or forbidden (403)
        self.assertIn(response.status_code, [302, 403])

    def test_non_admin_access_is_forbidden(self):
        """Verifies that non-admin roles (such as Volunteer) cannot access the certificate console."""
        self._login_as_volunteer()
        response = self.client.get('/admin/certificates/user-certificate')
        self.assertEqual(response.status_code, 403)

    def test_admin_can_access_user_certificate_page(self):
        """Verifies that an administrator can view both Issue and Active tabs of the certificate page."""
        self._login_as_admin()

        # 1. Test Issue Certificate Tab
        resp_issue = self.client.get('/admin/certificates/user-certificate?tab=issue')
        self.assertEqual(resp_issue.status_code, 200)
        self.assertIn(b'Members &amp; Certificates', resp_issue.data)
        self.assertIn(b'Generate Certificate', resp_issue.data)
        self.assertIn(b'SELECT TEMPLATE', resp_issue.data)

        # 2. Test Active Certificates Tab
        resp_active = self.client.get('/admin/certificates/user-certificate?tab=active')
        self.assertEqual(resp_active.status_code, 200)
        self.assertIn(b'Active Certificates', resp_active.data)

    def test_generate_certificate_with_all_six_templates(self):
        """
        Iteratively tests generating a certificate with each of the 6 distinct templates.
        Ensures each template generates successfully, stores record in DB, and assigns unique number.
        """
        self._login_as_admin()

        template_ids = [
            'template_1',  # Modern Sapphire
            'template_2',  # Golden Elegance
            'template_3',  # Executive Navy & Gold
            'template_4',  # Academic Royal Blue
            'template_5',  # Royal Prestige
            'template_6',  # Heritage Filigree
        ]

        for idx, tpl_id in enumerate(template_ids, start=1):
            recipient_name = f"Candidate {idx}"
            program_name = f"Special Welfare Initiative Level {idx}"
            member_code = f"NGO-2026-00{idx:02d}"

            response = self.client.post(
                '/admin/certificates/generate',
                data={
                    'recipient_name': recipient_name,
                    'member_code': member_code,
                    'program_name': program_name,
                    'template_id': tpl_id,
                    'recipient_email': f"candidate{idx}@test.org",
                    'recipient_phone': f"987654321{idx}",
                },
                headers={'X-Requested-With': 'XMLHttpRequest'}
            )

            self.assertEqual(response.status_code, 201)
            data = response.get_json()
            self.assertTrue(data['success'])
            self.assertIn('certificate', data)
            cert_no = data['certificate']['certificate_no']
            self.assertTrue(cert_no.startswith('CERT-2026-'))

            # Verify persisted record in DB
            db_cert = IssuedCertificate.query.filter_by(certificate_no=cert_no).first()
            self.assertIsNotNone(db_cert)
            self.assertEqual(db_cert.recipient_name, recipient_name)
            self.assertEqual(db_cert.template_id, tpl_id)
            self.assertEqual(db_cert.program_name, program_name)

    def test_standalone_certificate_view_renders_correctly(self):
        """Verifies that the standalone high-res certificate document renders with the chosen template styling."""
        self._login_as_admin()

        # 1. Generate a test certificate with Template 2 (Golden Elegance)
        gen_resp = self.client.post(
            '/admin/certificates/generate',
            data={
                'recipient_name': 'Khushi Maurya',
                'member_code': 'NGO-2026-0006',
                'program_name': 'Child Education & Literacy Camp',
                'template_id': 'template_2',
            },
            headers={'X-Requested-With': 'XMLHttpRequest'}
        )
        cert_no = gen_resp.get_json()['certificate']['certificate_no']

        # 2. View the certificate document
        view_resp = self.client.get(f'/admin/certificates/view/{cert_no}')
        self.assertEqual(view_resp.status_code, 200)
        self.assertIn(b'Khushi Maurya', view_resp.data)
        self.assertIn(b'Child Education &amp; Literacy Camp', view_resp.data)
        self.assertIn(b'cert-tpl-golden-vintage', view_resp.data)
        self.assertIn(b'Shri Ram Navyug Trust', view_resp.data)

    def test_public_qr_verification_of_issued_certificate(self):
        """Verifies that scanning the QR code or visiting /verify/<certificate_no> validates the certificate."""
        # 1. Issue a certificate as Admin
        self._login_as_admin()
        gen_resp = self.client.post(
            '/admin/certificates/generate',
            data={
                'recipient_name': 'Mohammad Ajaz',
                'member_code': 'NGO-2026-0001',
                'program_name': 'Disaster Relief Leadership',
                'template_id': 'template_1',
            },
            headers={'X-Requested-With': 'XMLHttpRequest'}
        )
        cert_no = gen_resp.get_json()['certificate']['certificate_no']

        # 2. Access the public verification portal without logging in
        self.client.get('/logout')
        verify_resp = self.client.get(f'/verify/{cert_no}')
        self.assertEqual(verify_resp.status_code, 200)
        self.assertIn(b'Officially Verified Certificate', verify_resp.data)
        self.assertIn(b'Mohammad Ajaz', verify_resp.data)
        self.assertIn(b'Disaster Relief Leadership', verify_resp.data)
        self.assertIn(b'Officially Valid &amp; Authentic', verify_resp.data)

    def test_delete_issued_certificate(self):
        """Verifies that an administrator can delete/revoke an issued certificate."""
        self._login_as_admin()

        # 1. Create certificate
        gen_resp = self.client.post(
            '/admin/certificates/generate',
            data={
                'recipient_name': 'Temporary Volunteer',
                'program_name': 'Temporary Program',
                'template_id': 'template_3',
            },
            headers={'X-Requested-With': 'XMLHttpRequest'}
        )
        cert_id = gen_resp.get_json()['certificate']['id']
        cert_no = gen_resp.get_json()['certificate']['certificate_no']

        # 2. Delete certificate
        del_resp = self.client.post(
            f'/admin/certificates/delete/{cert_id}',
            headers={'X-Requested-With': 'XMLHttpRequest'}
        )
        self.assertEqual(del_resp.status_code, 200)

        # 3. Verify certificate is removed from database
        deleted_cert = IssuedCertificate.query.get(cert_id)
        self.assertIsNone(deleted_cert)


if __name__ == '__main__':
    unittest.main()
