import os
import requests
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from database import get_db_connection

def test_fetch_reviews():
    creds = Credentials.from_authorized_user_file('token.json')
    if creds.expired and creds.refresh_token:
        creds.refresh(Request())

    headers = {
        'Authorization': f'Bearer {creds.token}'
    }

    account_url = "https://mybusinessaccountmanagement.googleapis.com/v1/accounts"
    res = requests.get(account_url, headers=headers)
    if res.status_code != 200:
        print("Error getting accounts:", res.text)
        return
        
    accounts = res.json().get('accounts', [])
    if not accounts:
        print("No accounts found.")
        return
        
    account_name = accounts[0]['name']
    print(f"Using account: {account_name}")
    
    conn = get_db_connection()
    with conn.cursor() as cur:
        cur.execute("SELECT outlet_name, popcorn_code, google_business_id FROM master_outlet WHERE google_business_id IS NOT NULL;")
        rows = cur.fetchall()
        for row in rows:
            name, code, loc_id = row
            location_name = f"locations/{loc_id.strip()}"
            url = f"https://mybusiness.googleapis.com/v4/{account_name}/{location_name}/reviews"
            response = requests.get(url, headers=headers)
            print(f"Outlet: {name} (Code: {code}, ID: {loc_id.strip()}) -> Status: {response.status_code}")
            if response.status_code == 200:
                data = response.json()
                reviews = data.get('reviews', [])
                print(f"  Found {len(reviews)} reviews.")
            else:
                print(f"  Error: {response.text[:200]}")
    conn.close()

if __name__ == '__main__':
    test_fetch_reviews()
