"""Payment Record endpoints — surfaces real accounting/fees data to the
`/admin/payment-record` page (previously mocked).
"""
import logging
from odoo import http
from odoo.http import request
from odoo.addons.encoach_api.controllers.base import (
    jwt_required, _json_response, _error_response,
)

_logger = logging.getLogger(__name__)


def _ser_fee_as_payment(rec):
    """Serialize an op.student.fees.details row as a 'payment record'."""
    inv = rec.invoice_id if hasattr(rec, 'invoice_id') else False
    return {
        'id': rec.id,
        'ref': f'FEE-{rec.id:04d}',
        'student_id': rec.student_id.id if rec.student_id else None,
        'student_name': rec.student_id.name if rec.student_id else '',
        'course_id': rec.course_id.id if rec.course_id else None,
        'course_name': rec.course_id.name if rec.course_id else '',
        'product_name': rec.product_id.name if rec.product_id else '',
        'amount': float(rec.amount or 0.0),
        'after_discount_amount': float(getattr(rec, 'after_discount_amount', rec.amount) or 0.0),
        'currency': rec.currency_id.name if hasattr(rec, 'currency_id') and rec.currency_id else 'USD',
        'state': rec.state or 'draft',
        'paid': rec.state in ('paid', 'post'),
        'date': str(rec.date) if rec.date else '',
        'type': 'Student Fees',
        'invoice_id': inv.id if inv else None,
        'invoice_number': inv.name if inv and inv.name and inv.name != '/' else '',
        'payment_state': inv.payment_state if inv and hasattr(inv, 'payment_state') else '',
    }


def _ser_invoice(inv):
    return {
        'id': inv.id,
        'ref': inv.name or f'INV-{inv.id}',
        'partner_name': inv.partner_id.name if inv.partner_id else '',
        'amount': float(inv.amount_total or 0.0),
        'currency': inv.currency_id.name if inv.currency_id else 'USD',
        'state': inv.state or 'draft',
        'payment_state': getattr(inv, 'payment_state', '') or '',
        'paid': getattr(inv, 'payment_state', '') == 'paid',
        'date': str(inv.invoice_date) if inv.invoice_date else str(inv.date) if inv.date else '',
        'type': 'Invoice',
    }


class PaymentRecordsController(http.Controller):

    @http.route('/api/payment-records', type='http', auth='public',
                methods=['GET'], csrf=False)
    @jwt_required
    def list_payments(self, **kw):
        """Return a unified list of payment records sourced from student fees
        (and optionally accounting invoices). Supports filters: status, paid,
        student_id."""
        try:
            FeesModel = request.env['op.student.fees.details'].sudo()
            domain = []
            status = kw.get('status')
            if status and status != 'all':
                domain.append(('state', '=', status))
            if kw.get('student_id'):
                try:
                    domain.append(('student_id', '=', int(kw['student_id'])))
                except (TypeError, ValueError):
                    pass
            recs = FeesModel.search(domain, limit=200)
            items = [_ser_fee_as_payment(r) for r in recs]
            paid_filter = kw.get('paid')
            if paid_filter in ('true', 'false'):
                want = paid_filter == 'true'
                items = [i for i in items if i['paid'] == want]
            return _json_response({
                'data': items,
                'items': items,
                'total': len(items),
                'totals': {
                    'count':  len(items),
                    'paid':   sum(1 for i in items if i['paid']),
                    'unpaid': sum(1 for i in items if not i['paid']),
                    'amount': sum(i['amount'] for i in items),
                },
            })
        except Exception as e:
            _logger.exception('list_payments')
            return _error_response(str(e), 500)

    @http.route('/api/payment-records/invoices', type='http', auth='public',
                methods=['GET'], csrf=False)
    @jwt_required
    def list_invoices(self, **kw):
        """Raw accounting invoices (account.move with out_invoice)."""
        try:
            Move = request.env['account.move'].sudo()
            domain = [('move_type', '=', 'out_invoice')]
            try:
                size = min(int(kw.get('size') or 50), 200)
            except (TypeError, ValueError):
                size = 50
            recs = Move.search(domain, limit=size, order='id desc')
            items = [_ser_invoice(m) for m in recs]
            return _json_response({
                'data': items, 'items': items, 'total': len(items),
            })
        except Exception as e:
            _logger.exception('list_invoices')
            return _error_response(str(e), 500)

    @http.route('/api/paymob-orders', type='http', auth='public',
                methods=['GET'], csrf=False)
    @jwt_required
    def list_paymob_orders(self, **kw):
        """Paymob integration is not yet wired — return empty list.
        This endpoint exists so the UI renders cleanly instead of calling a
        404-returning route."""
        return _json_response({
            'data': [], 'items': [], 'total': 0,
            'message': 'Paymob integration not configured.',
        })
