# -*- coding: utf-8 -*-

import re
import uuid

from odoo import api, fields, models


class ResUsers(models.Model):
    _inherit = 'res.users'

    x_fc_calendar_account_ids = fields.One2many(
        'fusion.calendar.account', 'x_fc_user_id',
        string='Connected Calendar Accounts',
    )
    x_fc_schedule_slug = fields.Char(
        string='Booking URL Slug',
        help='Unique slug for your public booking page, e.g. /schedule/john-doe',
        copy=False,
    )
    x_fc_booking_enabled = fields.Boolean(
        string='Public Booking Enabled',
        default=False,
        help='Allow external visitors to book your time via a public link.',
    )
    x_fc_work_start = fields.Float(
        string='Work Day Start', default=9.0,
        help='Start of your work day as decimal hours (e.g. 9.0 = 9:00 AM)',
    )
    x_fc_work_end = fields.Float(
        string='Work Day End', default=17.0,
        help='End of your work day as decimal hours (e.g. 17.0 = 5:00 PM)',
    )
    x_fc_break_start = fields.Float(
        string='Break Start', default=12.0,
        help='Fixed break/lunch start time (e.g. 12.0 = 12:00 PM)',
    )
    x_fc_break_duration = fields.Float(
        string='Break Duration (hours)', default=0.5,
        help='Break duration in hours (e.g. 0.5 = 30 minutes)',
    )
    x_fc_travel_buffer = fields.Integer(
        string='Travel Buffer (minutes)', default=30,
        help='Minimum travel buffer between appointments in minutes',
    )
    x_fc_home_address = fields.Char(
        string='Base/Office Address',
        help='Starting address for first appointment travel calculation',
    )
    x_fc_home_lat = fields.Float(string='Base Latitude', digits=(10, 7))
    x_fc_home_lng = fields.Float(string='Base Longitude', digits=(10, 7))

    _unique_schedule_slug = models.Constraint(
        'UNIQUE(x_fc_schedule_slug)',
        'This booking URL slug is already taken. Please choose a different one.',
    )

    @api.model_create_multi
    def create(self, vals_list):
        users = super().create(vals_list)
        for user in users:
            if not user.x_fc_schedule_slug:
                user.x_fc_schedule_slug = user._generate_schedule_slug()
        return users

    def _generate_schedule_slug(self):
        """Generate a URL-safe slug from the user's name."""
        self.ensure_one()
        name = self.name or 'user'
        # Normalize: lowercase, replace spaces with hyphens, remove special chars
        slug = re.sub(r'[^a-z0-9\-]', '', name.lower().replace(' ', '-'))
        slug = re.sub(r'-+', '-', slug).strip('-')
        if not slug:
            slug = 'user'
        # Add short unique suffix
        suffix = uuid.uuid4().hex[:4]
        return '%s-%s' % (slug, suffix)
