from django.test import TestCase, Client
from django.contrib.auth.models import User
from django.urls import reverse
from .models import Bookmark

class BookmarkTagUpdateTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(username='testuser', password='password')
        self.client = Client()
        self.client.login(username='testuser', password='password')
        self.bookmark = Bookmark.objects.create(
            user=self.user,
            url='https://example.com',
            title='Test Bookmark',
            notes='Test Notes'
        )
        self.bookmark.tags.add('initial')

    def test_update_tags(self):
        url = reverse('bookmark-edit', args=[self.bookmark.pk])
        
        data = {
            'url': 'https://example.com',
            'title': 'Updated Title',
            'notes': 'Updated Notes',
            'tags_input': 'updated, new-tag',
            # 'is_favorite': False # BooleanField handling in forms usually requires 'on' or missing.
            # If missing, it's false.
        }
        
        response = self.client.post(url, data)
        
        # Check for redirect (success)
        self.assertEqual(response.status_code, 302) 
        
        self.bookmark.refresh_from_db()
        self.assertEqual(self.bookmark.title, 'Updated Title')
        
        tags = list(self.bookmark.tags.names())
        tags.sort()
        self.assertEqual(tags, ['new-tag', 'updated'])

    def test_clear_tags(self):
        url = reverse('bookmark-edit', args=[self.bookmark.pk])
        data = {
            'url': 'https://example.com',
            'title': 'Updated Title',
            'notes': 'Updated Notes',
            'tags_input': '', # Empty tags
        }
        
        response = self.client.post(url, data)
        self.assertEqual(response.status_code, 302)
        
        self.bookmark.refresh_from_db()
        self.assertEqual(self.bookmark.tags.count(), 0)