-- Create table to track guard assignments to posts
-- Links guards to posts based on zone or individual assignment

CREATE TABLE IF NOT EXISTS guard_post_assignments (
    id INT AUTO_INCREMENT PRIMARY KEY,
    post_id INT NOT NULL,
    guard_id INT NOT NULL,
    assigned_by INT NOT NULL COMMENT 'User ID of person making assignment',
    assignment_start_date DATE NOT NULL,
    assignment_end_date DATE COMMENT 'NULL means ongoing',
    status ENUM('Active', 'Inactive', 'Completed') DEFAULT 'Active',
    notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    
    INDEX idx_post_id (post_id),
    INDEX idx_guard_id (guard_id),
    INDEX idx_assigned_by (assigned_by),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Add foreign keys after table creation to avoid constraint errors
ALTER TABLE guard_post_assignments ADD CONSTRAINT fk_post_id FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE;
ALTER TABLE guard_post_assignments ADD CONSTRAINT fk_guard_id FOREIGN KEY (guard_id) REFERENCES users(id) ON DELETE CASCADE;
ALTER TABLE guard_post_assignments ADD CONSTRAINT fk_assigned_by FOREIGN KEY (assigned_by) REFERENCES users(id) ON DELETE SET NULL;
