from flask import Blueprint, jsonify, request
from core.db import get_db
from services.report_service import get_donemsel_rapor
from datetime import date, timedelta

report_bp = Blueprint('report', __name__)


@report_bp.route('/api/rapor/donemsel')
def api_donemsel():
    try:
        aralik = request.args.get('aralik', 'bu_hafta')
        baslangic = request.args.get('baslangic', '')
        bitis = request.args.get('bitis', '')

        bugun = date.today()

        if aralik == 'bugun':
            baslangic = bitis = bugun.strftime('%Y-%m-%d')
        elif aralik == 'bu_hafta':
            baslangic = (bugun - timedelta(days=bugun.weekday())).strftime('%Y-%m-%d')
            bitis = bugun.strftime('%Y-%m-%d')
        elif aralik == 'bu_ay':
            baslangic = bugun.strftime('%Y-%m-01')
            bitis = bugun.strftime('%Y-%m-%d')
        elif aralik == 'ozel':
            if not baslangic or not bitis:
                return jsonify({'ok': False, 'hata': 'Tarih aralığı eksik'}), 400
        else:
            baslangic = (bugun - timedelta(days=6)).strftime('%Y-%m-%d')
            bitis = bugun.strftime('%Y-%m-%d')

        data = get_donemsel_rapor(baslangic, bitis)
        data['aralik'] = {'baslangic': baslangic, 'bitis': bitis}
        return jsonify({'ok': True, 'data': data})
    except Exception as e:
        return jsonify({'ok': False, 'hata': str(e)}), 500
